适配器模式
一、类适配器
public class ClassAdapterPattern { public class Adaptee { public void old_method() { System.out.println("This is an old method."); } } public interface Target{ public void new_method(); } public class Adapter extends Adaptee implements Target{ public Adapter(){ } public void new_method() { System.out.println("This is a new method."); } public void old_method() { super.old_method(); } } }
原来的接口本来就是一个类对象Adaptee且这个类也不是final类型,那么现在的适配器Adapter可以完全继承Adaptee,那么原来有的功能依然有,而且Adapter还实现Target接口,并实现里面的方法,那么Adapter就顺利的将Adaptee转换成Target了。
二、对象适配器
public interface AdapteeImpl{ public void old_method(); } public class Adaptee implements AdapteeImpl{ public void old_method() { System.out.println("This is an old method."); } } public interface Target{ public void new_method(); } public class Adapter implements AdapteeImpl ,Target{ AdapteeImpl adaptee; public Adapter(AdapteeImpl adaptee){ this.adaptee = adaptee; } public void new_method() { System.out.println("This is a new method."); } public void old_method() { adaptee.old_method(); } }
原来的需要转换的是一个接口AdapteeImpl,然后它会有实现类Adaptee,这时候就可以用对象适配器了,可以将原来的对象Adaptee作为构造函数的参数传入到对象中,那么以前的old_method可以用内部持有的Adaptee对象来进行调用,而仍然需要实现Target接口;


浙公网安备 33010602011771号