适配器模式

 

定义

将一个类的接口,转换为客户期望的另一个接口,而不需要修改源码。

使用

适配器模式可分为类适配器对象适配器,类适配器一般需要多重继承,Java 并不支持,我们暂不讨论。

适配器模式

其中,TargetInterface为客户需要的接口,Adaptee为需要适配的对象,Adapter为适配器,其实现需要的接口,并将要适配的对象包装起来,在调用目标接口的方法时,实际执行Adaptee对象的相应方法。

代码(Java)

// 要进行适配的类
public class Adaptee {
    public void specificRequest() {
        System.out.println("This is Adaptee specificRequest");
    }
}
​
// 所需要的目标接口
public interface TargetInterface {
    void request();
}
​
// 适配器类,负责将要适配的类转换为需要的接口
public class Adapter implements TargetInterface{
    private Adaptee adaptee;
​
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
​
    @Override
    public void request() {
        adaptee.specificRequest();
    }
}
​
// 测试客户类
public class Client {
    public static void main(String[] args) {
        TargetInterface target = new Adapter(new Adaptee());
        target.request();
    }
}

总结

适配器模式与装饰者模式比较类似,但是装饰者模式主要是添加新的功能,而适配器模式主要做的是转换工作。

适配器将一个对象包装起来以改变其接口;装饰者将一个对象包装起来以增加新的行为和责任