Decorator mode: The ability to dynamically extend an object without having to change the original class file and use inheritance. It is by creating a wrapper object, that is, decorating to wrap the real object
Features of decorative modes (1) The decorative object and the real object have the same interface. This allows the client object to interact with the adornment object in the same way as the real object.
(2) Decorative objects include a reference to a real object (reference)
(3) The Adornment object accepts all requests from the client.
It forwards these requests to the real object.
(4) The Adornment object can add some additional functions once or later in forwarding these requests. This ensures that at the time of execution. You can add additional functionality externally without altering the structure of a given object. In object-oriented design. Typically, inheritance is implemented to extend the functionality of a given class.
Applicability the following conditions use decorator mode
1. You need to extend the functionality of a class or add additional responsibilities to a class.
2. It is necessary to dynamically add functions to an object, which can be withdrawn dynamically.
3. It is necessary to add a large number of functions resulting from the combination of some basic functions. So that the inheritance relationship becomes unrealistic.
4. When the method of generating subclasses cannot be used for expansion. One scenario is that there may be a large number of independent extensions that will produce a large number of subclasses to support each combination, resulting in an explosive increase in the number of subclasses.
Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.
var Door = function () { } Door.prototype.open = function () { alert ("Open Door"); } var Decorator = function (Decorator) { this.decorator = Decorator; } Decorator.prototype.open = function () { this.decorator.open (); } var door = new Door (); var decorator = new Decorator (door); Decorator = new Decorator (decorator); Decorator.open ();
JS design mode decorator mode