ES6设计模式之装饰者模式

就是不修改原来的对象的情况下,对对象的功能进行扩充的一种方法。遵循的是开放封闭原则,类可以扩充但是不可以修改。 各种粥里面有不同的调料,不同的调料可以加不同的量,最后粥的价钱不等。下面是es实现:

// 注意粥里面可以加入不同的调料,调料不一样价钱不一样。

class Porridge{

constructor(){ this.ary_season = [] }

add(season){ this.ary_season.push(season); return this; }

// 不加任何调料2.8;

cost(){ return 2.8 + this.ary_season.reduce(function(prov,current){ return prov + current.cost(); },0); }

}

class beef{

constructor(number){ this.number = number; } // 牛肉单价10块。

cost(){ return this.number*10; }

}

class peanut{

constructor(number){ this.number = number; }

cost(){ return this.number*2; }

}

class egg{

constructor(number){ this.number = number; }

cost(){ return this.number*1; }

}

var myporride = new Porridge();

var price = myporride.add(new peanut(2)).add(new beef(0.4)).add(new egg(1)).cost();

console.log(price);

上面只是一个例子,装饰者的本质为对象增加功能而不触动开放封闭原则。

猜你喜欢

转载自www.cnblogs.com/node-jili/p/10161489.html