|
适配器模式定义: 将两个不兼容的类纠合在一起使用,属于结构型模式,需要有adaptee(被适配者)和adaptor(适配器)两个身份. 为何使用? 我们经常碰到要将两个没有关系的类组合在一起使用,第一解决方案是:修改各自类的接口,但是如果我们没有源代码,或者,我们不愿意为了一个应用而修改各自的接口。 怎么办? 使用adapter,在这两种接口之间创建一个混合接口(混血儿). 如何使用? 实现adapter方式,其实"think in java"的"类再生"一节中已经提到,有两种方式:组合(composition)和继承(inheritance). 假设我们要打桩,有两种类:方形桩 圆形桩. public class squarepeg{ public void insert(string str){ system.out.println("squarepeg insert():"+str); } } public class roundpeg{ public void insertintohole(string msg){ system.out.println("roundpeg insertintohole():"+msg); } }现在有一个应用,需要既打方形桩,又打圆形桩.那么我们需要将这两个没有关系的类综合应用.假设roundpeg我们没有源代码,或源代码我们不想修改,那么我们使用adapter来实现这个应用: public class pegadapter extends squarepeg{ private roundpeg roundpeg; public pegadapter(roundpeg peg)(this.roundpeg=peg;)< public void insert(string str){ roundpeg.insertintohole(str);} }在上面代码中,roundpeg属于adaptee,是被适配者.pegadapter是adapter,将adaptee(被适配者roundpeg)和target(目标squarepeg)进行适配.实际上这是将组合方法(composition)和继承(inheritance)方法综合运用. pegadapter首先继承squarepeg,然后使用new的组合生成对象方式,生成roundpeg的对象roundpeg,再重载父类insert()方法。从这里,你也了解使用new生成对象和使用extends继承生成对象的不同,前者无需对原来的类修改,甚至无需要知道其内部结构和源代码. 如果你有些java使用的经验,已经发现,这种模式经常使用。
进一步使用 上面的pegadapter是继承了squarepeg,如果我们需要两边继承,即继承squarepeg 又继承roundpeg,因为java中不允许多继承,但是我们可以实现(implements)两个接口(interface) public interface iroundpeg{ public void insertintohole(string msg); } public interface isquarepeg{ public void insert(string str); }下面是新的roundpeg 和squarepeg, 除了实现接口这一区别,和上面的没什么区别。 public class squarepeg implements isquarepeg{ public void insert(string str){ system.out.println("squarepeg insert():"+str); } } public class roundpeg implements iroundpeg{ public void insertintohole(string msg){ system.out.println("roundpeg insertintohole():"+msg); } }下面是新的pegadapter,叫做two-way adapter: public class pegadapter implements iroundpeg,isquarepeg{ private roundpeg roundpeg; private squarepeg squarepeg; // 构造方法 public pegadapter(roundpeg peg){this.roundpeg=peg;} // 构造方法 public pegadapter(squarepeg peg)(this.squarepeg=peg;) public void insert(string str){ roundpeg.insertintohole(str);} }还有一种叫pluggable adapters,可以动态的获取几个adapters中一个。使用reflection技术,可以动态的发现类中的public方法。
|