关于javascript:适配器装饰器

6次阅读

共计 2344 个字符,预计需要花费 6 分钟才能阅读完成。

js 设计模式 – 适配器模式、装璜器模式

1. 适配器模式

适配器模式:(Adapter)是将一个类的接口转化成客户心愿的另外一个接口,Adapter 模式使得本来因为接口不兼容而不能一起工作的那些类能够一起工作。(大话设计模式)
应用场景:零碎的数据和行为都正确,但接口不符时,咱们应该思考用适配器,目标时使管制范畴之外的一个原有对象与某个接口匹配。适配器模式次要利用于心愿复用现存的类,但时接口又与服用环境要求不统一的状况。(大话设计模式)
JavaScript 毕竟不是传统基于面向对象的语言 因而应用 es6 class 关键字(不应用 typescript)创立的适配器会和 Java、C#、VB.NET 的适配器有些许的差别(本文不进行探讨)。

1.1 特定适配器模式

  class MyInterface {constructor(arr) {this.arr = arr}
    getResult() {return this.arr}
  }
  class MySonInterface extends MyInterface {transform() {return this.arr.reduce(function(pre,cur,index,arr) {pre['date' + index] =  cur
        return pre
      },{})
    }
  }
  var int = new MyInterface([7,2,3,4,5]) 
  var myint = new MySonInterface([7,2,3,4,5])
  console.log(int.getResult()); // [7, 2, 3, 4, 5]
  console.log(myint.transform()); // {date0: 7, date1: 2, date2: 3, date3: 4, date4: 5}

1.2 通用适配器模式

  class Adapter{constructor(arr) {this.obj = new MyInterface(arr)
    }
    transform() {return this.obj.arr.reduce(function(pre,cur,index,arr) {pre['date' + index] =  cur
        return pre
      },{})
    }
  }
  var ide = new Adapter([7,2,3,4,5])
  console.log(ide.transform()); // {date0: 7, date1: 2, date2: 3, date3: 4, date4: 5}

1.3 工厂适配器模式

  class AdapterFactor {static create (Interface, arr) {return new Interface(arr)
    }
  }
  var ide2 = AdapterFactor.create(Adapter, [7,2,3,4,5])
  console.log(ide2.transform()); // {date0: 7, date1: 2, date2: 3, date3: 4, date4: 5}

2. 装璜器模式

装璜器模式 (Decorator Pattern): 装璜器模式是指容许一个现有的对象增加新的性能,同时又不扭转其构造。使得不同类或者对象之间共享或者扩大一些办法或者行为的时候,更加优雅
应用场景:

2.1 继承实例(❌)

为什么要写一个谬误的实例呢?
起因:
1. 传统的面向对象的语法中,须要给一个对象新增性能时,咱们通常应用的都是类的继承来使某一类对象领有某个性能。
2. 装璜模式(Decorator): 动静地给一个对象增加一些额定的职责,就减少性能来说,装璜模式比生成子类更灵便。(大话设计模式)

  class Cat {constructor(name) {this.name = name}
    sayName() {console.log('猫咪的名字是',this.name);
    }
  }
  class SuperCat extends Cat {constructor(name,age) {super(name)
      this.age = age
    }
    sayAge() {console.log('超级猫咪往年',this.age);
    }
  }
  var cat1 = new Cat('思乡')
  var nbCat = new SuperCat('思凡',2)
  nbCat.sayName() // 猫咪的名字是 思凡
  nbCat.sayAge()  // 超级猫咪往年 2
  cat1.sayName() // 猫咪的名字是 思乡

因为继承所带来的强耦合性,也导致生成的类有着致命的毛病‘灵活性低’,当咱们批改父类的某个属性就会导致子类随之产生更改,由此能够看出类的继承与装璜器模式的区别(如果没有了解,请看装璜器模式的定义)

2.2 装璜器模式实例

  class Dog {constructor(name) {this.name = name}
    sayName() {console.log('狗狗的名字是',this.name);
    }
  }
  class SuperDog {constructor(dog) {this.dog = dog}
    sayName() {this.dog.sayName()
    }
    sayNewname() {console.log('降级后的超级狗狗领有了新的名字','超级' + this.dog.name);
    }
  }
  var dog = new Dog('旺财')
  var superDog = new SuperDog(dog)
  superDog.sayName() // 狗狗的名字是 旺财 
  superDog.sayNewname() // 降级后的超级狗狗领有了新的名字 超级旺财
  dog.sayName() // 狗狗的名字是 旺财 

由下面的后果能够看进去咱们调用 superDog 的办法的同时咱们不仅调用了 superDog 的办法也调用了 Dog 的办法,咱们只是对其中的 Dog 进行了一个包装,让咱们能在应用 Dog 类外部办法的同时,咱们也能定义新的办法

正文完
 0