javascript设计模式-装饰者模式(9)
来源:互联网 发布:邢台羊毛衫知乎 编辑:程序博客网 时间:2024/03/29 19:59
装饰者是一种为对象添加新特性的技术,它并不适用创建新子类的这种手段。装饰者模式可以用来透明的把对象包装在具有同样接口的另一个对象之中。这样我们就可以为对象添加一个方法或者一些行为,然后将方法调用传递给原始对象。
//装饰者模式:就是在保证不改变原有对象的基础上,去扩展一些想要的方法或去求//实现同样的借口//需要有子类var CarInterface = new BH.Interface('CarInterface' , ['getPrice' , 'assemble']);var Car = function(car){ //就是为了让子类继承 (让子类 多一个父类的引用) this.car = car ; //检查接口 BH.Interface.ensureImplements(this , CarInterface);};Car.prototype = { constructor :Car, getPrice:function(){ return 200000 ; }, assemble:function(){ document.write('组装汽车...'); }};//新的需求:light、icebox ....... var LightDecorator = function(car){ //原始对象 //借用构造函数继承 LightDecorator.superClass.constructor.call(this , car); }; BH.extend(LightDecorator , Car); //原型继承 LightDecorator.prototype = { constructor:LightDecorator , getPrice:function(){ return this.car.getPrice() + 10000; }, assemble:function(){ document.write('组装车灯...'); } }; var IceBoxDecorator = function(car){ //借用构造函数继承 IceBoxDecorator.superClass.constructor.call(this , car); }; BH.extend(IceBoxDecorator , Car); //原型继承 IceBoxDecorator.prototype = { constructor:IceBoxDecorator , getPrice:function(){ return this.car.getPrice() + 20000; }, assemble:function(){ document.write('组装车载冰箱...'); } };
在父类中的this.car = car 会被子类继承,在子类中使用this.car就是父类中car的引用
//装饰者 不仅可以用在类上, 还可以用在函数上 //返回一个当前时间的字符串表示形式function getDate(){ return (new Date()).toString();};// 包装函数 (装饰者函数)function upperCaseDecorator(fn){ return function(){ return fn.apply(this, arguments).toUpperCase(); }};alert(getDate());var getDecoratorDate = upperCaseDecorator(getDate);alert(getDecoratorDate());
阅读全文