javascript设计模式-装饰着模式
装饰者模式,Decorator Pattern。在不改变原类和继承的情况下动态扩展对象功能,通过包装一个对象来实现一个新的具有原对象相同接口的新的对象。
装饰者模式特点:
1. 不修改原对象的原本结构来进行功能添加。
2. 装饰对象和原对象具有相同的接口,可以使客户以与原对象相同的方式使用装饰对象。
3. 装饰对象中包含原对象的引用,即装饰对象为真正的原对象在此包装的对象。
装饰者模式可以为对象添加功能从而代替了编写大量子类的情况。
以JS设计模式实例为例,首先自行车商店有4种类型自行车:
<!DOCTYPE HTML>
<html>
<body>
<script>
function ABicycle(){ }
ABicycle.prototype = {
wash : function(){ },
ride : function(){ },
getPrice : function(){
return 999;
}
}
function extend( subClass, superClass ){
var F = function(){};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
// 此处指向superClass的prototype 比直接保存superClass使用更为方便
subClass.superclass = superClass.prototype;
if( superClass.prototype.constructor === Object.prototype.constructor ){
superClass.prototype.constructor = superClass;
}
}
function BicycleDecorator( bicycle ){
this.bicycle = bicycle;
}
BicycleDecorator.prototype = {
wash : function(){
return this.bicycle.wash();
},
ride : function(){
return this.bicycle.ride();
},
getPrice : function(){
return this.bicycle.ride();
}
}
var BicycleBell = function( bicycle ){
// 继承 BicycleDecorator 内部 this定义的数据或者方法
BicycleBell.superclass.constructor( bicycle );
}
// 继承 BicycleDecorator.prototype 并且添加 BicycleBell.superclass 指向 BicycleDecorator.prototype
extend( BicycleBell, BicycleDecorator );
// 添加或者修改
BicycleBell.prototype.bell = function(){
console.log("ding! ding! ding!");
}
BicycleBell.prototype.getPrice = function(){
console.log(this)
return this.bicycle.getPrice() + 100;
}
var bicycleA = new ABicycle();
bicycleA = new BicycleBell( bicycleA );
console.log(bicycleA.getPrice());
</script>
</body>
</html>

浙公网安备 33010602011771号