Home >Web Front-end >JS Tutorial >JavaScript design pattern seven: Decorator pattern
This article shares with you the seventh JavaScript design pattern: Decorator pattern. Friends who are interested can take a look at
The Decorator pattern provides more flexibility than inheritance. alternatives. Decorators are used to wrap objects with the same interface and add new functions in the form of overloaded methods. This mode can add your own behavior before or after the decorated object to achieve a specific purpose.
Simple understanding: The way of dynamically adding responsibilities to an object is called the decorated mode.
Give a simple example:
var xiaoming = function () { this.run = function () { return '跑步' }, this.eat = function () { return: '吃饭' } } // 小明可以跑步,也可以吃饭 // 下面是一个装饰类,给小明进行装饰 var decor = function (xiaoming) { this.run = function () { return xiaoming.run + '很快' } this.eat = function () { return xiaoming.eat + '很多' } }
Through a decoration class, the decoration of Xiao Ming class is realized.
The decorator pattern is a way to dynamically add more functions to existing functions. Put each function to be decorated in a separate function, and then use that function Wraps the existing function object to be decorated. Therefore, when special behavior needs to be performed, the calling code can selectively and sequentially use the decoration function to wrap the object as needed. The advantage is that the core responsibilities of the class (function) and the decoration function are separated
Related recommendations:
JavaScript Design Pattern Series 2: Singleton Pattern
JavaScript Design Pattern Series 4: Prototype Mode
JavaScript Design Pattern Series 6: Bridge Mode
The above is the detailed content of JavaScript design pattern seven: Decorator pattern. For more information, please follow other related articles on the PHP Chinese website!