zoukankan      html  css  js  c++  java
  • 设计模式之—适配器模式

    1.适配器模式的定义

    Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.

    将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够一起工作。

    2.通用类图

    适配器模式中有三个主要对象。

    Target:

    转换成的目标接口,即将其他类转换为此Target接口
    

    Adaptee:

    被转换的类
    

    Adapter:

    适配器,通过实现Target接口并继承Adaptee类,并重写Target接口方法来实现适配
    

    类图如下:

    实现代码如下:
    Target类:

    public interface Target {
    
        /**
         * request
         */
        void request();
    }
    

    Adaptee类:

    public class Adaptee {
    
        public void doSomething(){
            System.out.println("Do something!");
        }
    }
    

    Adapter类:

    public class Adapter extends Adaptee implements Target {
    
        @Override
        public void request() {
            doSomething();
        }
    }
    

    Client类:

    public class Client {
    
        public static void main(String[] args) throws Exception {
            Target target = new Adapter();
            target.request();
        }
    }
    

    3.优点

    1.可以使两个无关联的类一起运行
    2.灵活性好,当不需要此适配器的时候,只需要将此类摘除掉即可

    4.总结

    适配器模式通常用来解决在功能变动时,解决接口不相容的问题,在系统设计阶段不应该使用此中模式

  • 相关阅读:
    【LeetCode】085. Maximal Rectangle
    哈希查找
    堆排序
    归并排序
    希尔排序
    快速排序
    堆区和栈区,malloc和new的区别
    C++基础
    二分查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/vitasyuan/p/9571237.html
Copyright © 2011-2022 走看看