二、建造者模式_适配器设计模式
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
相关文章推荐
- java设计模式(一)——适配器、桥接、建造者、职责链、命令
- 设计模式-建造者模式详解
- 设计模式笔记1——适配器Adapter模式
- 设计模式之禅【建造者模式】
- [Head First设计模式]山西面馆中的设计模式——建造者模式
- 设计模式05-建造者模式
- java设计模式之适配器设计模式
- JAVA设计模式之适配器
- 设计模式(3) - Builder建造者模式
- 设计模式之建造者模式
- 设计模式 建造者模式 Builder
- C++设计模式之建造者模式(二)
- java设计模式-建造者模式
- 设计模式 - 单例模式、建造者模式
- [设计模式]建造者模式
- Java设计模式之建造者模式
- 设计模式之适配器模式
- c#设计模式- Builder模式(建造者模式)
- 设计模式之建造者模式(Builder)
- java设计模式(工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式、适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式,。 行为型模式,共十一种:策略模式、模板方法)