JS design mode 7: decorator Mode

Source: Internet
Author: User

JS design mode 7: decorator Mode

Decorator Pattern. The object function is dynamically extended without changing the original class and inheritance. By packing an object, a new object with the same interface of the original object is implemented.

Decoration Mode features: 1. Add functions without modifying the original structure of the original object.
2. The decoration object has the same interface as the original object, so that the customer can use the decoration object in the same way as the original object.
3. The decoration object contains the reference of the original object, that is, the decoration object is the real original object packaged here.

The modifier mode can be used to add functions for objects, instead of writing a large number of child classes.
Taking the JS design model as an example, there are four types of bicycles in the bicycle store:

 
 
  1. var ABicycle = function(){ ... };
  2. var BBicycle = function(){ ... };
  3. var CBicycle = function(){ ... };
  4. var DBicycle = function(){ ... };

When a bicycle store needs to provide additional functions or accessories for each type of bicycle, such as headlights, baskets, and color changes, the most basic way is to create a subclass for each combination, for example, A type A car with bells, A Type B car with yellow bells, and A type C car with A basket,

 
 
  1. var ABicycleWithBell = function(){ ... };
  2. var BBicycleWithColorYellow = function(){ ... };
  3. var CBicycleWithColorBule = function(){ ... };
  4. ...

Indeed, it is just like the feeling you see at first glance. This method is decisive and unreliable, n types of configuration, at the end, the 4n + 4 types (including the original 4 parent classes) will be generated, which is never desirable.

Of course, our first possible idea is that we can set the color, the car basket or something as an instance property and control the generation by the passed parameters in the class. This is indeed good, no problem, however, some function extensions may be insufficient, such as the speed control function, brake enhancement function, and anti-theft function added to bicycles, it is easier to use the modifier mode to add these functions (if it is more embedded in the class, it will be processed by passing parameters, in the case of many features, it is obviously not reliable ).

First, we need A class of basic bicycle.

 
 
  1. function ABicycle(){ }
  2. ABicycle.prototype = {
  3. wash : function(){ },
  4. ride : function(){ },
  5. getPrice : function(){
  6. return 999;
  7. }
  8. }

The next step is to set a bell for the bicycle and the function of ringing the bell:
The simplest thing is to directly wrap the object instance:

 
 
  1. function bicycleBell( bicycle ){
  2. var price= bicycle.getPrice();

  3. bicycle.bell = function(){
  4. console.log("ding! ding! ding!");
  5. };

  6. bicycle.getPrice = function(){
  7. return price + 100;
  8. };
  9. return bicycle;
  10. }

Use

 
 
  1. var bicycleA = new ABicycle();
  2. bicycleA = bicycleBell( bicycleA );

In the following format:

 
 
  1. bicycle.getPrice = function(){
  2. return bicycle.getPrice() + 100;
  3. };

Of course, this form will lead to infinite loop calls ~

Indeed, this packaging method is not to wrap the object into a constructor again, but to adjust the instance object, which is both convenient and simple. However, it is not a problem for returning constant data results like the getPrice method, you can save it in the form of a closure.
However, if the function needs to be called in the packaging and saved in the form of a closure, it will be cumbersome and unchanged.

So let's look at the decoration method below:

 
 
  1. function BicycleBell( bicycle ){
  2. this.bicycle = bicycle;
  3. }

  4. BicycleBell.prototype = {
  5. wash : function(){
  6. return this.bicycle.wash();
  7. },
  8. ride : function(){
  9. return this.bicycle.ride();
  10. },
  11. getPrice : function(){
  12. return this.bicycle.ride() + 100;
  13. },
  14. bell : function(){
  15. console.log("ding! ding! ding!");
  16. }
  17. }

Package the instance, simulate the original class again, encapsulate the instance as a parameter, and provide the same interface as the original class. This method solves some methods that need to be modified and depend on the original method. Of course, it also has its own shortcomings. This decoration is too cumbersome, and all, such as acceleration, color switching, and the decoration of the car basket or anything, must be in such a form, and the code will be a little messy.

So, extract it.
First, an inherited method is required, and the prototype pointing to the parent class is required.

 
 
  1. Function extend (subClass, superClass ){
  2. Var F = function (){};
  3. F. prototype = superClass. prototype;
  4. SubClass. prototype = new F ();
  5. SubClass. prototype. constructor = subClass;

  6. // Prototype pointing to superClass is more convenient than directly saving superClass
  7. SubClass. superclass = superClass. prototype;
  8. If (superClass. prototype. constructor === Object. prototype. constructor ){
  9. SuperClass. prototype. constructor = superClass;
  10. }
  11. }

Then, each decoration person can depend on the inherited intermediate decoration person:

 
 
  1. function BicycleDecorator( bicycle ){
  2. this.bicycle = bicycle;
  3. }
  4. BicycleDecorator.prototype = {
  5. wash : function(){
  6. return this.bicycle.wash();
  7. },
  8. ride : function(){
  9. return this.bicycle.ride();
  10. },
  11. getPrice : function(){
  12. return this.bicycle.ride();
  13. }
  14. }

Then it's clever to use extend.

 
 
  1. Var BicycleBell = function (bicycle ){
  2. // Inherit the data or method defined by this in BicycleDecorator
  3. BicycleBell. superclass. constructor. call (this, bicycle );
  4. }
  5. // Inherit the BicycleDecorator. prototype and add the BicycleBell. superclass to point to the BicycleDecorator. prototype
  6. Extend (BicycleBell, BicycleDecorator );
  7. // Add or modify
  8. BicycleBell. prototype. bell = function (){
  9. Console. log ("ding! Ding! Ding! ");
  10. }
  11. BicycleBell. prototype. getPrice = function (){
  12. Return this. bicycle. getPrice () + 100;
  13. }

Use the same method for instance Packaging

 
 
  1. var bicycleA = new ABicycle();
  2. bicycleA = new BicycleBell( bicycleA );

The above method is a better form of annotator mode. More comprehensive interfaces may need to be obtained through the original class Traversal method when defining the BicycleDecorator and BicycleDecorator. prototype objects.

Of course, these methods can be used as needed. Targeted processing is the most effective solution.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.