装饰器模式--设计模式之js运用
1、装饰器模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
2、js使用
1)实现被装饰者
//被装饰者 Circle Circle.js function Circle(){ this.name = "Circle"; } Circle.prototype={ draw:function(){ console.log("Circle==draw"); } }//被装饰者 Rectangle Rectangle.js
function Rectangle(){
this.name = "Rectangle";
}
Rectangle.prototype={
draw:function(){
console.log("Rectangle==draw");
}
}
2)实现装饰者
/** * 装饰者 color Color.js * @constructor */ function Color(decoratored){ this.decoratored = decoratored; this.extends2(decoratored); }Color.prototype.setColor = function(s){
console.log("对被装饰者:"+this.decoratored.name+";设置color:"+s);
}/**
- 装饰者 size Size.js
- @constructor
*/
function Size(decoratored){
this.decoratored = decoratored;
this.extends2(decoratored);
}
Size.prototype.setSize = function(s){
console.log("对被装饰者:"+this.decoratored.name+";设置Size:"+s);
}
3)test
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="../base.js"></script> <script src="Rectangle.js"></script><script src="Circle.js"></script> <script src="Size.js"></script> <script src="Color.js"></script> </head> <body> <script> var rect = new Rectangle();var circle = new Circle(); var rs = new Size(rect); var rc = new Color(rs); rc.draw(); rc.setSize(20); rc.setColor("red");var cs = new Size(circle); var cc = new Color(cs); cc.draw(); cc.setSize(200); cc.setColor("red"); </script>
</body>
</html>
结果:
标题:装饰器模式--设计模式之js运用
作者:hugh0524
地址:https://blog.uproject.cn/articles/2016/06/01/1464752089025.html
0 0