定义
适配器模式是把一个类的接口转换成客户所期望的另一种接口,从而使原本不匹配而无法在一起工作的两个类可以一起工作。
UML
角色
- Target: 符合客户端期望的接口。
- Adaptee: 需要被适配的类。此类包含了客户端想要实现的大部分功能,但并不能完成客户端所想完成的所有任务,同时又不能被直接修改,因此需要被适配。
- Adapter: 适配器类。继承了Adaptee类的方法,如function1(),同时又实现了Target接口。适配器使得相互不兼容的Target和Adaptee能在Adapter中一起配合完成工作。
类适配器示例
UML中的表示即为类适配器的实现
/**
* desc : 被适配的类
* Created by tiantian on 2018/10/2
*/
public class Adaptee {
public void function1() {
System.out.println("I'm function1() who can do something, tut not enough.");
}
}
/**
* desc : 目标接口
* Created by tiantian on 2018/10/2
*/
public interface Target {
void function1();
void function2();
}
/**
* desc : 类适配器
* Created by tiantian on 2018/10/2
*/
public class Adapter extends Adaptee implements Target{
@Override
public void function2() {
System.out.println("I'm function2() who can do another thing.");
}
}
/**
* desc : 测试
* Created by tiantian on 2018/10/2
*/
public class Test {
public static void main(String[] args) {
Target adapter = new Adapter();
adapter.function1();
adapter.function2();
}
// I'm function1() who can do something, tut not enough.
// I'm function2() who can do another thing.
}
对象适配器示例
对象适配器实现了Target接口,并组合了被适配类Adaptee类,使之能完成接口所期望的功能。
/**
* desc : 对象适配器
* Created by tiantian on 2018/10/2
*/
public class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void function1() {
adaptee.function1();
}
public void function2() {
System.out.println("I'm function2() who can do another thing.");
}
}
总结
实际开发中对象适配器更为常用,因为就设计原则而言,组合的方式更灵活易用,方便扩展。组合的方式实现的对象适配器可以动态的向Adapter中注入Adatpee子类的对象。而使用继承的类适配器则可以覆盖Adaptee中的实现,具体使用哪种适配器,还是看具体的业务场景,因地制宜。