js设计模式 --- 适配设计模式

适配模式

定义:适配器模式将某个类的接口转换成客户端期望的另一个接口表示,主的目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。

原有的两个类由于接口不一, 需要对其中一个类进行适配包装, 以供与另外的类进行沟通匹配

实现适配模式有两种, 继承和桥接, 后者本人更喜欢

  • 继承结构:
    《js设计模式 --- 适配设计模式》
  • 实现

    • 220v接口

      //类适配器模式
      var v220 = new Interface('v220', ['output220V']);
    • 220v电源类

      let Voltage220 = function() {
      };
      Voltage220.prototype.output220V = function() {
        let src = 220;
        console.log("我是" + src + "V");
        return src;
      }
    • 5v接口

      var v5 = new Interface('v5', ['output5V']);
    • 适配类

      let VoltageAdapter = function () {
        Voltage220.call(this);
      }
      // 实现5v接口
      VoltageAdapter.prototype.output5V = function() {
        let src = this.output220V();
        console.log("适配器工作开始适配电压");
        let dst = src / 44;
        console.log("适配完成后输出电压:" + dst);
        return dst;
      }
      extend(VoltageAdapter, Voltage220);
  • 继承结构:
    《js设计模式 --- 适配设计模式》
  • 实现

    • 适配类

      let VoltageAdapter2 = function (voltage220) {
        this.mVoltage220 = voltage220;
      };
      VoltageAdapter2.prototype.output5V = function () {
        let dst = 0;
        if (null != this.mVoltage220) {
            let src = this.mVoltage220.output220V();
            console.log("对象适配器工作,开始适配电压");
            dst = src / 44;
            console.log("适配完成后输出电压:" + dst);
        }
        return dst;
      }

对象适配器和类适配器其实算是同一种思想,只不过实现方式不同。

根据合成复用原则,组合大于继承, 第二种优于第一种,它解决了类适配器必须继承src的局限性问题.

    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000013329416
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞