裝飾者模式,Decorator Pattern。在不改變原類和繼承的狀況下動態擴展對象功能,經過包裝一個對象來實現一個新的具備原對象相同接口的新的對象。
javascript
1. 不修改原對象的本來結構來進行功能添加。
2. 裝飾對象和原對象具備相同的接口,能夠使客戶以與原對象相同的方式使用裝飾對象。
3. 裝飾對象中包含原對象的引用,即裝飾對象爲真正的原對象在此包裝的對象。
裝飾者模式能夠爲對象添加功能從而代替了編寫大量子類的狀況。
以JS設計模式實例爲例,首先自行車商店有4種類型自行車:html
<!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>