您的位置:首页 > 其它

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

2018-09-13 20:10 281 查看
原文链接:http://www.cnblogs.com/jiarui-zjb/p/9642828.html

1、建造者模式:
    工厂类模式提供的是创建单个类的模式,而建造者模式则是将各种产品集中起来进行管理,用来创建复合对象,所谓复合对象就是指某个类具有不同的属性,其实建造者模式就是前面抽象工厂模式和最后的 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 测试类

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

2、适配器设计模式
    适配器模式将某个类的接口转换成客户端期望的另一个接口表示, 目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式
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 类的实例,以达到解决兼容性的问题。

public class Adapter2  implements Targetable {
private Source source;

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

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

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

}
View Code

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

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

运行结果:

 

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

 

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


转载于:https://www.cnblogs.com/jiarui-zjb/p/9642828.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: