The definition of Decorator Pattern :

Decorator (decorator) Patterns can be created without changing the object itself , Add responsibility to the object dynamically during the running of the program . Compared with inheritance , Decorator is a more light and flexible way .

The characteristics of the decorator model :

You can dynamically add additional responsibilities to an object , Without affecting other objects derived from this class ;

Some of the shortcomings of inheritance :

  1. Inheritance leads to strong coupling between superclasses and subclasses , When the superclass changes , Subclasses change as well ;

  2. The inner details of a superclass are visible to subclasses , Inheritance is often thought to break encapsulation ;

Traditional object-oriented decorators and JavaScript Comparison of decorators :

1. Simulate the decorator pattern of traditional object-oriented language

// The decorator who imitates traditional language
// The original airplane class 
var Plan = function () {
}; Plan.prototype.fire = function () {
console.log(' Fire ordinary bullets ');
}; // Decoration
var MissileDecorator = function (plan) {
this.plan = plan;
} MissileDecorator.prototype.fire = function () {
this.plan.fire();
console.log(' Launch missiles !');
}; var plan = new Plan();
plan = new MissileDecorator(plan);
plan.fire();

2.JavaScript Decorator mode in

Decorator mode embeds one object into another , It's actually equivalent to the object being wrapped by another object , Form a packaging chain . Requests are passed to all objects in turn along the wrapper chain , Every object has an opportunity to process this request .


var Plan1 = {
fire: function () {
console.log(' Fire ordinary bullets ');
}
}; var missileDecorator= function () {
console.log(' Launch missiles !');
}; var fire = Plan1.fire; Plan1.fire=function () {
fire();
missileDecorator();
}; Plan1.fire();

Decoration function

stay JavaScript You can easily extend properties and methods to an object in , But it's hard to do without changing the source code of a function , Add some extra functionality to this function . That is, while the code is running , It's hard to cut into the execution environment of a function .

1. Using the decorator pattern example

// Yes window.onload To deal with
window.onload=function () {
console.log('test');
}; var _onload= window.onload || function () {}; window.onload=function () {
_onload();
console.log(' Your own processing functions ');
};

2. Use AOP( Section oriented programming ) Decoration function

The main idea is that JavaScript With the call of the function ,this It's a change of direction , Cause the result of execution to change .

2.1. Packaged before function

Execute a newly added function before the function to be executed

// Is the newly added function executed before the old function 
Function.prototype.before=function (beforefn) {
var _this= this; // Save references to old functions
return function () { // Returns... That contains the old function and the new function “ agent ” function
beforefn.apply(this,arguments); // Execute the new function , And guarantee this Not hijacked , The parameters accepted by the new function
// It will also be passed into the old function intact , The new function is executed before the old function
return _this.apply(this,arguments);
};
};
2.2. Packaged after function

Execute a newly added function after the function to be executed


// The newly added function is executed after the old function
Function.prototype.after=function (afterfn) {
var _this=this;
return function () {
var ret=_this.apply(this,arguments);
afterfn.apply(this,arguments);
return ret;
};
};
2.3. No pollution Function Prototype approach
var before=function (fn, before) {
return function () {
before.apply(this,arguments);
return fn.apply(this,arguments);
};
}; function func1(){console.log('1')}
function func2() {console.log('2')} var a=before(func1,func2); // a=before(a,func1);
a();

Examples of decorator pattern usage :

1.ajax Add parameters dynamically

Use decorator mode dynamic change ajax function , Parameters of transmission

// Is the newly added function executed before the old function 
Function.prototype.before=function (beforefn) {
var _this= this; // Save references to old functions
return function () { // Returns... That contains the old function and the new function “ agent ” function
beforefn.apply(this,arguments); // Execute the new function , And guarantee this Not hijacked , The parameters accepted by the new function
// It will also be passed into the old function intact , The new function is executed before the old function
return _this.apply(this,arguments);
};
}; var func = function (param) {
console.log(param);
}; func = func.before(function (param) {
param.b = 'b';
}); func({b:'222'}); // to ajax An example of a request to dynamically add parameters
var ajax=function (type,url,param) {
console.log(param);
}; var getToken=function () {
return 'Token';
}; ajax=ajax.before(function (type, url, param) {
param.token=getToken();
}); ajax('get','http://www.jn.com',{name:'zhiqiang'});

2. Form validation and submission

Decorator mode separates form validation and submission functions

Function.prototype.before=function (beforefn) {
var _this= this; // Save references to old functions
return function () { // Returns... That contains the old function and the new function “ agent ” function
beforefn.apply(this,arguments); // Execute the new function , And guarantee this Not hijacked , The parameters accepted by the new function
// It will also be passed into the old function intact , The new function is executed before the old function
return _this.apply(this,arguments);
};
}; var validata=function () {
if(username.value===''){
alert(' The username cannot be empty !')
return false;
}
if(password.value===''){
alert(' The password cannot be empty !')
return false;
}
} var formSubmit=function () {
var param={
username=username.value;
password=password.value;
} ajax('post','http://www.mn.com',param);
} formSubmit= formSubmit.before(validata); submitBtn.onclick=function () {
formSubmit();
}

summary :

The difference between decorator mode and agent mode :

  1. The purpose of the agency model is , When direct access to ontology is inconvenient or does not meet the needs , Provide a substitute for this ontology . Ontology defines key functions , And the agent offers or denies access to him , Or do something extra before accessing the ontology .

  2. The function of decorator mode is to dynamically add certain behaviors to objects .


 
 
 

JavaScript Design patterns ---- More about decorator mode

  1. javascript Design patterns —— Decorator mode

    In front of the word In program development , Most of the time, you don't want a class to be huge by nature , One time involves many responsibilities . So you can use decorator mode . Decorator mode can dynamically add additional responsibilities to an object , Without affecting other objects derived from this class . This article will ...

  2. from ES6 Reunderstanding JavaScript Design patterns : Decorator mode

    1 What is the decorator mode Add new functionality to an existing object , The design pattern without changing its structure is called decorator pattern (Decorator Pattern), It is a wrapper for existing classes (Wrapper). The decorator can be understood as ...

  3. Book notes - javascript Design patterns - Decorator mode

    This chapter discusses a technique for adding features to objects , It doesn't use the means of creating new subclasses . Decorator mode can transparently wrap an object in another object with the same interface , thus , You can add some behavior to some methods , Then pass the method call to the original object . ...

  4. JavaScript Design patterns — Decorator mode

    Decorator mode introduction Add new functionality to objects , Without changing its original structure and function , The original function can still be used , Different from adapter mode , The original adapter mode is no longer available , Examples of decorators are mobile phone cases UML Class diagrams and code examples Circle Show the original ...

  5. JavaScript Design pattern ---- Portfolio model

    javascript Composite pattern of design patterns Introduce A composite pattern is one that is designed to create Web A dynamic user interface on the web . Using this pattern, you can fire complex or recursive behavior on multiple objects with a single command . This can simplify the stickiness code , Make it more ...

  6. Java Design patterns —— Decorator mode

    JAVA Design patterns Decorator mode purpose Decorator mode (Decorator) Dynamically add some additional responsibilities to an object . In terms of adding functionality ,Decorator Patterns are more flexible than subclasses . The decorator model is a structural model ...

  7. JAVA Design patterns -- Decorator mode

    Decorator mode Decorator mode (Decorator Pattern) Allows new functionality to be added to an existing object , Without changing its structure . This type of design pattern belongs to structural pattern , It is a wrapper for existing classes . This pattern creates a decoration ...

  8. javascript The decorator mode of Decorator

    It's a bit of a twist at first , Now look back ,so easy! Function.prototype.before = function(beforefn){ var _self = this; retur ...

  9. From the perspective of source code Java Design patterns —— Decorator mode

    One . Introduction to the decorator model Decorator pattern definition : Add functions without changing the original object , More flexible than subclassing . Applicable scenario : Add or remove functions to an object dynamically . advantage : You can extend the function dynamically without changing the original object , You can extend multiple ...

Random recommendation

  1. DatatableToJson JsonToDatatable

    using Newtonsoft.Json;using Newtonsoft.Json.Converters; /// <summary> /// take DataTable Type to JSON type ...

  2. spring MVC、mybatis Configure read-write separation

    spring MVC.mybatis Configure read-write separation 1. Environmental Science : 3 Database machines , One master, Two sets slave, Respectively slave1,slave2 2. The goal to achieve : ① Write data to master ② reading ...

  3. day10-redis operation

    Redis redis It's a key-value The storage system . and Memcached similar , It supports storage value There are more types , Include string( character string ).list( Linked list ).set( aggregate ).zset(sorte ...

  4. [ACM_ The geometric ] UVA 11300 Spreading the Wealth [ Share the gold coin Left and right It's equal in the end Equations Median ]

    Problem A Communist regime is trying to redistribute wealth in a village. They have have decided to ...

  5. Python Basics (10)-- Numbers

    The theme of this article is Python Number in . Each number type will be described in detail , The various operators they apply to , And built-in functions for processing numbers . At the end of the article , This paper briefly introduces several modules used in the standard library to process numbers . This paper addresses :http:// ...

  6. docker offical docs:Working with Docker Images

    Working with Docker Images ##orignal is always the best In the introduction we've discovered that Do ...

  7. android Customize the photo storage location after taking photos with the camera

    1.imageUri = Uri.fromFile(new File(Environment .getExternalStorageDirectory()+ File.separator + getP ...

  8. Java Use httpclient Post And cxf released Webservice signal communication

    Use cxf released webservice I don't know what will work sometimes, sometimes not , It's definitely not going to work for the project . I don't want to change it webservice Because there's so much code . Lazy people ! So we use httpclient And webservic ...

  9. Python Basic character coding

    Preface Character coding is very prone to problems , We need to keep a few words in mind : 1. In what code , We're going to open it with some code 2. Execution of procedures , Read the file into memory first 3.unicode It's the parent code , Can only encode Decode into other encoding formats utf ...

  10. Tomcat Console UTF-8 The code problem

    1. modify cmd The encoding format of Shortcut key win+R Open the running program , Input regedit Open the registry , Find the following Lu Jin and modify . [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Comman ...