JS 设想形式 十二(装潢着形式)

装潢器形式

对客户通明的体式格局动态地给一个对象附加上更多的义务,同时又不转变其构造。装潢形式能够在不运用制造更多子类的情况下,将对象的功用加以扩大。

装潢器要素

1.笼统构件(Component)角色:给出一个笼统接口,以范例预备吸收附加义务的对象。
2.详细构件(ConcreteComponent)角色:定义一个将要吸收附加义务的类。
3.装潢(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与笼统构件接口一致的接口。
4.详细装潢(ConcreteDecorator)角色:担任给构件对象“贴上”附加的义务。

例子

咖啡,可加牛奶,也可加糖,或许都加。

//装潢着形式    
var DP = require("./DesignPattern.js");

function Icoffee() {
  DP.Interface(this, ['showCoffee', 'getPrice']);
}

function Coffee(name, price) {
  this.__proto__ = new Icoffee();
  var _name, _price;
  _name = name;
  _price = price;
  this.showCoffee = function () {
    console.log(_name + 'coffee');
  }
  this.getPrice = function () {
    return _price;
  }
}

function Decorator(Coffee) {
  var _coffee;
  _coffee = Coffee;
  this.showCoffee = function () {
    _coffee.showCoffee();
  }
  this.getPrice = function () {
    return _coffee.getPrice();
  }
}

function Sugar(Coffee) {
  this.__proto__ = new Decorator(Coffee);
  this.showCoffee = function () {
    console.log('加糖');
    this.__proto__.showCoffee();
  }
  this.getPrice = function () {
    return this.__proto__.getPrice() + 5;
  }
}

function Milk(Coffee) {
  this.__proto__ = new Decorator(Coffee);
  this.showCoffee = function () {
    console.log('加牛奶');
    this.__proto__.showCoffee();
  }
  this.getPrice = function () {
    this.__proto__.getPrice();
    return this.__proto__.getPrice() + 5;
  }
}

var coffee = new Coffee("拿铁", 20);

var sugar = new Sugar(coffee);
sugar.showCoffee();
console.log(sugar.getPrice());
console.log('--------------------------------------------');
var milk = new Milk(coffee);
milk.showCoffee();
console.log(milk.getPrice());
console.log('--------------------------------------------');
var sugarmilk = new Milk(sugar);
sugarmilk.showCoffee();
console.log(sugarmilk.getPrice());
console.log('--------------------------------------------');
var sugarmilkmilk = new Milk(sugarmilk);
sugarmilkmilk.showCoffee();
console.log(sugarmilkmilk.getPrice());

装潢器形式长处:

1.装潢类和被装潢类能够自力生长,不会互相耦合。
2.装潢形式是继续的一个替换形式,装潢形式能够动态扩大一个完成类的功用。就增添功用来讲,装潢器形式比拟天生子类更加天真。

实用场景:

1.扩大一个类的功用。
2.动态增添功用,动态打消。

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