Continue to learn hard PS: learn from — nuggets of JavaScript design pattern core principle and application booklet

Introduce a,

  • 1. The concept

On the basis of not changing the original object, the original object can meet the more complex needs of users by packaging and expanding it.

  • 2. For example

In the era of artificial intelligence, our company made a robot, this robot, can sweep the floor can patrol. Later, due to a war in a certain country, we need to customize our robots to meet the requirements of combat. 0.0. At that point, we changed the robot to war robot. Then another order came in asking us to deliver, so we developed it again. And then… Countless business, our company should be made. A lot of people have left, AND I’m going to leave, too. The new staff has handed over to me, and I don’t know much about the stuff inside. The original product has changed a lot, and the project is getting harder and harder to maintain. My boss won’t let me go and bought me a house in Shanghai (wake up young man).

Second, code analysis

  • 1. Initialize the robot

Create robot humans with cleaning and patrolling functions

Recognize () {class Robot {// Initialize ability to recognize () {this.clean(); this.patrol(); } // clean clean() {console.log(' cleaning, version '); } // Patrol () {console.log(' patrol ')}} const robot = new robot (); robot.initAbility()Copy the code

Print result:



  • 2. Create a war decorator that allows you to fight

Has the ability to wear armor and fire weapons

Constructor (obj) {this.obj = obj; constructor(obj) {this.obj = obj; } initAbility() { this.obj.initAbility(); this.handleDeco(); } handleDeco() {this.corselet() {console.log(' I am wearing armor '); } // Fire weapons arms() {console.log(' fire weapons '); }} // Decorate with decorator const robot2 = new Robot(); const fightRobot = new FightDecorator(robot2); fightRobot.initAbility()Copy the code

Print result:

  • 3. Create a takeout robot decorator

It can deliver food and connect meituan system

class TakeAwayDecorator { constructor(obj) { this.obj = obj; } initAbility() { this.obj.initAbility(); this.handleDeco() } handleDeco() { this.bike(); this.system(); } // Bike () {console.log(' I am a bike robot '); } system() {console.log(' I can connect to meituan system '); } } const robot3 = new Robot(); const takeAwayDecorator = new TakeAwayDecorator(robot3); takeAwayDecorator.initAbility()Copy the code

Print result:

PS: ES7 decorator syntax sugar & React HOC will be introduced after I review webpack packaging and React