适配器模式(结构型)

来源:互联网 发布:南国英雄传 知乎 编辑:程序博客网 时间:2024/06/05 20:14
适配器模式的定义:将一个类的接口转换成客户希望的另外一个接口,适配器模式使得原本因为接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式的本质:转换匹配、复用功能
适配器模式的类别:类适配器、对象适配器
客户端和相关领域的接口:
public interface Target {
    //客户端请求处理的方法
    public void request();
}
适配器:吧Adaptee适配成客户端需要的Target
public class Adapt implements Target {
    private Adaptee adaptee;
    public Adapt(Adaptee adaptee){
        this.adaptee = adaptee;
    }
    public void request() {
        adaptee.specificRequest();
    }
}
已存在的接口:通常能满足客户端的功能需求,但是不符合客户端所需要的接口
public class Adaptee {
    //具体实现的方法
    public void specificRequest(){
        System.out.println("已存在的接口,满足客户的功能需求");
    }
}
客户端:调用袭击需要的领域接口Target
public class Client {
    public static void main(String [] args){
        Target target = new Adapt(new Adaptee());
        target.request();
    }
}


优点:
更好的复用性:仅仅是接口不想容,适配器可以让这些功能得到更好的复用
更好的扩展性:可以扩展系统的功能
缺点:
过多的使用会使系统变得凌乱、复杂。不容易整体把握
参考博文:
http://www.cnblogs.com/wangjq/archive/2012/07/09/2582485.html
http://haolloyin.blog.51cto.com/1177454/346128
0 0
原创粉丝点击