Home >Web Front-end >JS Tutorial >Detailed explanation of js decoration design pattern

Detailed explanation of js decoration design pattern

小云云
小云云Original
2018-02-22 09:11:021290browse

Decoration design mode:

Each device has its own unique application scenarios and ways to solve problems. The decoration design mode dynamically adds new functions to the object. , is a technique used to replace inheritance and extend the new functionality of an object 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 class


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();
  }
}

Extension class


  var HeadlightDecorator = function(bicycle){
    BicycleDecorator.call(this, bicycle);
  };
  extend(HeadlightDecorator, BicycleDecorator);
  HeadlightDecorator.prototype.getPrice = function(){
    return this.bicycle.getPrice() + 15.00;
  }

Related recommendations:

##Instance analysis of common basic design patterns in Node.js

Detailed explanation of the service locator pattern example of PHP design pattern

Detailed explanation of the memo pattern of PHP design pattern

The above is the detailed content of Detailed explanation of js decoration design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn