“This is the 27th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
introduce
The decorator pattern, which dynamically adds additional responsibilities to an object without affecting the functionality of the principle, is a common design pattern that is more flexible than subclassing, and is an alternative to inheritance.
For chestnut, contra believe we have played as a child, leading role in the process of the mobile will eat to all kinds of BUFF, after eating weapon will change, have a plenty of shotguns, have a plenty of fire, have a plenty of the laser and so on all kinds of effect, but shooting action execution does not change, change is only the weapon shooting effect, You can use decorator mode to append/change these weapon effects.
concept
The decorator pattern is a structural pattern that acts as a wrapper around an existing class. This allows you to add new functionality to an existing object without changing its structure.
case
Next, is to achieve a contra weapon switch.
var player = {
fire:function(){
console.log("- Execute the shot -")}}var weaponS = function(){
console.log("* Shotgun weapon *")}var weaponF = function(){
console.log("* Fire-breathing weapons *")}var weaponL = function(){
console.log(* Laser weapon *)}var _player_fire = player.fire;
player.fire = function(){
_player_fire();
weaponS();
}
player.fire()
console.log("~~~~~~ Switch weapons ~~~~~~~")
player.fire = function(){
_player_fire();
weaponF();
}
player.fire()
console.log("~~~~~~ Switch weapons ~~~~~~~")
player.fire = function(){
_player_fire();
weaponL();
}
player.fire()
Copy the code
As you can see here, we haven’t changed the player’s original action. We’ve just expanded the weapon’s functionality, and the switch doesn’t affect the original shooting action.
ES a decorator
Because there really is a lot of business involved in decorator patterns, a new syntax for decorators was introduced in ES7.
A decorator is a function named @ +.
It can be placed in front of class and class method definitions, and can be conveniently used to decorate the entire class.
@decorator
class className {}
/ / is equivalent to
class className {}
className = decorator(className) || className;
Copy the code
See Ruan Yifeng’s Introduction to ECMAScript 6 for details
However, it is still a proposal at present, and it is still unknown whether there will be any changes in the future.
Usage scenarios
- Extend the functionality of a class.
- Dynamic add function, dynamic undo.
conclusion
It is not difficult to find from what has just been said that the decorated class and the decorated class can develop independently and will not be coupled with each other. The decorated pattern is an inherited alternative pattern, and the decorated pattern can dynamically extend the functions of an implementation class, which is very flexible.
We can consider using it in development, such as log statistics, avatar box decoration replacement and so on.