• 适配器模式


     

    定义

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

    使用

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

    总结

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

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

  • 相关阅读:
    Ubuntu下安装mysql
    MySQL聚集索引与非聚集索引
    mysql索引的简单介绍
    Hive数据导入与导出
    hive的基本操作
    hive的数据模型
    29 ArcMap许可服务器点击授权后无法进入下一步
    28 ArcMap 运行特别慢怎么办
    27 ArcMap加载天地图服务一片空白怎么办
    26 Arcpy跳坑系列——ExportToPNG
  • 原文地址:https://www.cnblogs.com/zawier/p/7196478.html
Copyright © 2020-2023  润新知