What are design patterns? Why use design patterns?
Design pattern is a general solution in software development process (23), not a special language, is a programming idea.
In general, we should follow the rule of “use composition more than inheritance” in code design. Add some additional responsibilities to an object dynamically through the decorator pattern. In terms of adding functionality, the decorator pattern is more flexible than subclassing, making code more elegant.
A decorator
Allows you to add a new function to an object without changing the original object. Decorators use @ as an identifier and are placed in front of the code to be decorated.
Colloquially speaking, people wear different clothes in different seasons. People are the objects and clothes are decorators.
Decorator original implementation
Draw () {console.log(" draw a Circle ")}} /** draw a Circle (do not change the original class) ** / class DarwBord {constructor (circle) {this.circle = circle} // Draw () {this.circle. Draw (); DrawBord () {console.log(" drawBord "); this.drawbord () {console.log(" drawBord "); } } const circle = new Circle() const drawBoard = new DarwBord(circle) drawBoard.draw()Copy the code
Decorator —- Annotated form (Note: ES6 does not recognize annotation decorator @run. Decorator is a class-related syntax for annotating or modifying classes and class methods, a proposal in the latest ECMA
)
// decorator ---- annotate form class Boy {@run // Annotate decorator speak () {console.log(' I can sing ')}} /** * decorator * @param target Boy object * @param key Function run (Target, key, descriptor) {console.log(target, key, descriptor) Descriptor) console.log(" I can run ")} const boy = new boy () boy.speak()Copy the code
Decorator —- adds logs to methods
Add (a, b) {return a + b}} function log (target, name, descriptor) { const oldValues = descriptor.value; Value = function () {// Arguments js Built-in objects include all arguments to this function console.log(' call ${name} ') Parameters: ', arguments) //target scope return oldValues. Apply (target, arguments) arguments) } console.log(descriptor) return descriptor } const math = new Math(); math.add(1, 3)Copy the code
Decorator —- with parameters
Class Math {@log(100) // Add (a, B) {return a + b}} function log (num) {// descriptor) { const _num = num || 0; // const oldValues = descriptor.value; //oldValues = function (...); //oldValues = function (...); Arg) {arg[0] += _num arg[1] += _num //arguments JS Built-in objects include all arguments to this function console.log(' call ${name} argument: ', arg) //target scope return oldValues. Apply (target, arg) } console.log(descriptor) return descriptor } } const math = new Math(); console.log(math.add(1, 3))Copy the code
Code repository address gitee.com/wangsf1/dec…