设计模式之装饰器模式
装饰器模式
需求
- 4s店在卖一种车,价格为10万元,如果用户需要在此基础上加装一些配置则需要加钱。
- 比如加热座椅配置需要2万元,电动车后视镜需要0.8万元等等。
function Car() {
this.price = 10;
}
Car.prototype = {
addHeatSeat: function() {
this.hasHeatSeat = true;
this.price += 2;
},
addAuthoMirror: function() {
this.hasAutoMirror = true;
this.price += 0.8;
}
}
const car1 = new Car();
console.log(car1.price); // 10
car1.addHeatSeat();
car1.addAuthoMirror();
console.log(car1.price); // 12.8
装饰器写法
function Car() {
this.price = 10;
}
function addHeatSeat(carClass) {
carClass.hasHeatSeat = true;
carClass.price += 2;
}
function addAuthoMirror(carClass) {
carClass.hasAutoMirror = true;
carClass.price += 0.8;
}
const car1 = new Car();
console.log(car1.price); // 10
addHeatSeat(car1);
addAuthoMirror(car1);
console.log(car1.price); // 12.8
- 装饰器优点:
- 并不会修改和破坏原有的构造函数拓展功能
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14322418.html