首页 > 其他 > 详细

适配器模式

时间:2017-07-17 17:56:45      阅读:258      评论:0      收藏:0      [点我收藏+]

 

定义

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

使用

适配器模式可分为类适配器对象适配器,类适配器一般需要多重继承,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();
    }
}

 

总结

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

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

 

适配器模式

原文:http://www.cnblogs.com/zawier/p/7196478.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!