This article will share with you the author’s experience and key points after learning the Javascript decoration design pattern. Friends who are interested can refer to it.
Decoration design mode
Each device has its own unique application scenarios and ways to solve problems. The decoration design mode dynamically adds new objects to the object. Function, is a technology used to replace inheritance, which can extend the new functions of objects without adding subclasses through inheritance. Using the association relationship of objects instead of inheritance relationship is more flexible and avoids the rapid expansion of the type system. This mode is suitable for use when the newly added functions are not enough to solve the problem at the expense of inheritance - killing a chicken with a butcher's knife ^_^
Decoration design pattern: Dynamically add some additional responsibilities to an object. To extend the functionality of an object, decorators provide a more flexible alternative than inheritance.
Structure diagram:
Interface
var Bicycle = new Interface('Bicycle', ['assemble', 'wash', 'repair', 'getPrice']);
Object class
var AcmeComfortCuiser = function(){ }; AcmeComfortCuiser.prototype = { assemble: function(){ }, wash: function(){ }, repair: function(){ }, getPrice: function(){ } }
Decoration Category
var BicycleDecorator = function(bicycle){ Interface.ensureImplements(bicycle, Bicycle); this.bicycle = bicycle; }; BicycleDecorator.prototype = { assemble: function(){ return this.bicycle.assemble(); }, wash: function(){ return this.bicycle.wash(); }, repair: function(){ return this.bicycle.repair(); }, getPrice: function(){ return this.bicycle.getPrice(); } }
Expansion Category
var HeadlightDecorator = function(bicycle){ BicycleDecorator.call(this, bicycle); }; extend(HeadlightDecorator, BicycleDecorator); HeadlightDecorator.prototype.getPrice = function(){ return this.bicycle.getPrice() + 15.00; }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. help.
Related articles:
Using JS callback function case description
Using JS callback function case description
nodejsBuild a local server to handle cross-domain processing
The above is the detailed content of js decoration design pattern learning experience (detailed answers). For more information, please follow other related articles on the PHP Chinese website!