适配器模式
适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题
类的适配器
UML
Java
- 编写Source类,拥有一个方法,待适配:
public class Source { public void method1() { System.out.println("this is original method!"); } }
- 定义目标接口Targetable:
public interface Targetable { /* 与原类中的方法相同 */ void method1(); /* 新类的方法 */ void method2(); }
- ClassAdapter类继承Source类,实现Targetable接口
public class Adapter extends Source implements Targetable { public void method2() { System.out.println("this is the targetable method!"); } }
- 测试类:
public class ClassAdpaterTest { public static void main(String[] args) { Targetable target = new Adapter(); target.method1(); target.method2(); } }
- 测试结果:
this is original method! this is the targetable method!
这样Targetable接口的实现类就具有了Source类的功能
对象的适配器
将Adapter类作修改,这次不继承Source类,而是持有Source类的实例
UML
Java
- 只需要修改Adapter类的源码:
public class ObjectAdapter implements Targetable { private Source source; public ObjectAdapter(Source source) { super(); this.source = source; } public void method2() { System.out.println("this is the targetable method!"); } public void method1() { source.method1(); } }
- 测试类:
public class ObjectAdapterTest { public static void main(String[] args) { Source source = new Source(); Targetable target = new ObjectAdapter(source); target.method1(); target.method2(); } }
- 测试结果:
this is original method! this is the targetable method!