适配器模式
动机(Motivation)
➢在软件系统中,由于应用环境的变化,常常需要将“一些现存的对象”放在新的环境中应用,但是这些现存对象不满足新环境要求的接口。
➢如何应对这种“迁移的变化”?如何既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口?
适配器( Adapter)模式
- 变压器( Adapter) :把一种电压变换成另一种电压。美国的生活用电电压是110V,而中国的电压是220V。如果要在中国使用美国电器,就必须有一个能把220V电压转换成110V电压的变压器。这个变压器就是一个Adapter。
- 适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一一起工作的两个类能够在一起工作。
适配器模式的两种形式
适配器adapter
适配者adaptee:需要适配的类
- 类适配器模式:适配器与适配者之间是继承(或实现)关系;
- 对象适配器模式:适配器与适配者之间是关联关系。
//Target(这是客户所期待的接口)
class Target{
public void Request() {
System.out.println("普通请求!");
}
}
//Adaptee(需要适配的类)
class Adaptee{
public void SpecificRequest() {
System.out.println("特殊请求!");
}
}
class Adapter extends Target{
private Adaptee adaptee=new Adaptee();
public void Request() {
adaptee.SpecificRequest();
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Target target=new Adapter();
target.Request();
}
}
interface ITarget{
default void Request() {
}
}
//Adaptee(需要适配的类)
class Adaptee{
public void SpecificRequest() {
System.out.println("特殊请求!");
}
}
class Adapter extends Adaptee implements ITarget{
public void Request() {
this.SpecificRequest();
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ITarget target=new Adapter();
target.Request();
}
}
在以下各种情况下使用适配器模式
- 系统需要使用现有的类,而此类的接口不符合系统的需要。
- 想要建立一个可以重复使用的类,该类可能与其它不相关的类或不可预见的类( 即那些接口可能不一定兼容的类)协同工作。
- (对对象适配器而言)在设计里,想使用一些已经存在的子类,但是不可能对每一个子类都进行适配。对象适配器可以适配它们的父类接口。
本质
●转换匹配,复用功能