设计模式-装饰模式
装饰模式是为类添加额外的职责。在我看来,这些职责并不是某一个类特有,需要添加的类都可以添加,每个类没有必要单独添加这个职责。
下面是我用js实现的装饰模式
var Employee={ name: '', getName: function(){ return this.name; }, setName: function(name){ this.name = name; }, work: function(){} } function CosmeticsSalesEmployee(name){ this.name = name; this.work = function(){ alert(this.getName() + " 开始销售化妆品!"); } } function FruitSalesEmployee(name){ this.name = name; this.work = function(){ alert(this.getName() + " 开始销售水果!"); } } CosmeticsSalesEmployee.prototype = Employee; FruitSalesEmployee.prototype = Employee; var cosmeticsSalesEmployee1 = new CosmeticsSalesEmployee("小王"); cosmeticsSalesEmployee1.work(); //输出: 小王 开始销售化妆品 var fruitSalesEmployee = new FruitSalesEmployee("小张"); fruitSalesEmployee.work(); //输出 小张 开始销售水果
//装饰类 var Decorator = { employee: null, setEmployee: function(e){ this.employee = e; }, getEmployee: function(){ return this.employee; }, getName: function(){ return this.employee ? this.employee.getName() : undefined; }, work: function(){ this.employee && this.employee.work(); } } function ArrangeGoodDecorator(employee){ Decorator.setEmployee(employee); this.work = function(){ alert(this.getName() + "开始清扫货架!"); Decorator.work(); } } ArrangeGoodDecorator.prototype = Decorator; var employee1 = new ArrangeGoodDecorator(new CosmeticsSalesEmployee("小王")); employee1.work(); //输出:
//小王开始清扫货架!
//小王 开始销售化妆品!
var employee2 = new ArrangeGoodDecorator(new FruitSalesEmployee("小张")); employee2.work();
//小张开始清扫货架!
//小张 开始销售水果!