首页 > 其他 > 详细

适配器模式

时间:2014-07-12 14:14:10      阅读:296      评论:0      收藏:0      [点我收藏+]

    适配器模式(Adapter Pattern)就是对一个类做适配,使之符合客户端的需求,能够正常的工作。

    就像是变压器(Adapter),美国的生活电压是110V,中国的是220V,美国的电器要在中国使用就需要加上一个变压器(Adapter)。

    适配器模式也被称为包装模式(Wrapper Pattern),将已有的类进行包装,使之具有需求所需的接口。

    适配器模式有以下两种:类的适配器模式和对象的适配器模式。

    bubuko.com,布布扣

    类的适配器模式的类图关系如下:

    bubuko.com,布布扣

       Target:目标角色,包含所有期望拥有的接口

       Adaptee:现有的类,需做适配

       Adapter:适配Adaptee符合Target      

public interface Target {   
    void sampleOperation1();
    void sampleOperation2();
}

  

public class Adaptee {
    public void sampleOperation1(){}
}

  

public class Adapter extends Adaptee implements Target {
   
    public void sampleOperation2(){
        // Write your code here
    }
}

  对象的适配器模式的类图关系如下:

 bubuko.com,布布扣

    对象的适配器模式与类的适配器模式的区别在于: Adapter与Adaptee的关系不是继承,而是关联。 Adapter直接调用Adaptee。

public class Adapter implements Target {
    public Adapter(Adaptee adaptee){
        super();
        this.adaptee = adaptee;
    }

    public void sampleOperation1(){
        adaptee.sampleOperation1();
    }

    public void sampleOperation2(){
        // Write your code here
    }

    private Adaptee adaptee;
}

  

适配器模式,布布扣,bubuko.com

适配器模式

原文:http://www.cnblogs.com/lnlvinso/p/3839826.html

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