2、建造者模式_适配器设计模式

一、建造者模式:
    工厂类模式提供的是建立单个类的模式,而建造者模式则是将各类产品集中起来进行管理,用来建立复合对象,所谓复合对象就是指某个类具备不一样的属性,其实建造者模式就是前面抽象工厂模式和最后的 Test 结合起来获得的。
1.1 建造者模式类设计模式

public class Builder {
    private List<Sender> list=new ArrayList<Sender>();
    
    public void produceMailSender(int count){
        for(int i=0;i<count;i++){
            list.add(new MailSender());
        }
    }
    
    public void produceSmsSender(int count){
        for(int i=0;i<count;i++){
            list.add(new SmsSender());
        }
    }
}
View Code

1.2 测试类ide

public class TestBuilder {
    public static void main(String[] args) {
        Builder builder=new Builder();
        builder.produceMailSender(2) ;
    }
}    
View Code

二、适配器设计模式
    适配器模式将某个类的接口转换成客户端指望的另外一个接口表示, 目的是消除因为接口不匹配所形成的类的兼容性问题。主要分为三类:类的适配器模式对象的适配器模式接口的适配器模式
2.1类适配器Adapter1:
    将Source(自己是一个类,能够将其理解为某个业务类处理这样的一个接口)类的接口,转化成客户端指望的另外一个接口(Targetable),目的是消除因为接口不匹配所形成的类的兼容性问题测试

public class Source {
    public void method1() {
        System.out.println("这是原类Source类中的方法method1");
    }
}
    
public interface Targetable {
    /*与Source(原类)中的方法相同 */
    public void method1();

    /* 新类的方法 */
    public void method2();
}
//经过继承Source类,实现Targetable接口,消除了Source类和接口Targetable之间不匹配的问题  
public class Adapter1 extends Source implements Targetable {
    public void method2() {
        System.out.println("这是目标接口targetable中的 method2方法!");
    }

}
View Code

2.2 对象适配器Adapter2:基本思路和类的适配器模式相同,只是将Adapter类作修改,此次不继承 Source 类,而是持有 Source 类的实例,以达到解决兼容性的问题。ui

public class Adapter2  implements Targetable {
    private Source source;

    public Adapter2(Source source) {
        super();
        this.source = source;
    }

    public void method1() {
        source.method1();
    }

    public void method2() {
        System.out.println("this is the targetable method!");
    }

}
View Code

类适配器和对象适配器的测试类:this

public class Test {
    public static void main(String[] args) {
        /*类适配器测试:*/
        Targetable target=new Adapter1();
        target.method1();
        target.method2();
        /*对象的适配器模式*/    
        Source source=new Source();
        Targetable target2=new Adapter2(source);
        target2.method1();
        target2.method2();
        
    }
}
View Code

运行结果:spa

 

这是原类Source类中的方法method1
这是目标接口targetable中的 method2方法!
这是原类Source类中的方法method1
this is the targetable method!
View Code

 

2.3 接口的适配器是这样的:有时咱们写的一个接口中有多个抽象方法,当咱们写该接口的实现类时,必须实现该接口的全部方法,这明显有时比较浪费,由于并非全部的方法都是咱们须要的,有时只须要某一些,此处为了解决这个问题,咱们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了全部的方法,而咱们不和原始的接口打交道,只和该抽象类取得联系,因此咱们写一个类,继承该抽象类,重写咱们须要的方法就行。


设计

相关文章
相关标签/搜索