Github source address

Design patterns

Introduction to the

  • Design Patterns (Design patternIn 1994, the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) published a book entitledDesign Patterns - Elements of Reusable Object-Oriented SoftwareDesign Patterns, Reusable Object-oriented Software Elements, was the first to introduce the concept of design patterns in software development.
  • Is a set of repeated, well-known, catalogued code design lessons.

purpose

  • Reuse code;
  • Code is easier for others to understand;
  • Ensure code reliability.

classification

  • A total of23Are divided into three categories:Creational Patterns), structural mode (Structural Patterns), behavioral patterns (Behavioral Patterns).
Creation pattern
  • Factory Model (Factory Pattern)
  • Abstract Factory Pattern (Abstract Factory Pattern)
  • Singleton pattern (Singleton Pattern)
  • Builder model (Builder Pattern)
  • Prototype pattern (Prototype Pattern)
Structural mode
  • Adapter mode (Adapter Pattern)
  • Bridge mode (Bridge Pattern)
  • Combined mode (Composite Pattern)
  • Decorator mode (Decorator Pattern)
  • Appearance mode (Facade Pattern)
  • Premium Mode (Flyweight Pattern)
  • Proxy mode (Proxy Pattern)
Behavioral pattern
  • Chain of Responsibility Model (Chain of Responsibility Pattern)
  • Command mode (Command Pattern)
  • Interpreter mode (Interpreter Pattern)
  • Iterator pattern (Iterator Pattern)
  • The Intermediary Model (Mediator Pattern)
  • Memo Mode (Memento Pattern)
  • Observer mode (Observer Pattern)
  • State mode (State Pattern)
  • Strategic Mode (Strategy Pattern)
  • Template mode (Template Pattern)
  • Visitor Pattern (Visitor Pattern)

The six principles

1. Open and close principle (Open Close Principle)
  • Open closed principle: Open for extensions, closed for modifications. When the program needs to be extended, you cannot modify the original code to achieve a hot plug effect. In short, to make the program extensible, easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes.
2. Richter’s Substitution Principle (Liskov Substitution Principle)
  • Richter’s substitution principle is one of the basic principles of object-oriented design. Wherever a base class can appear, a subclass must appear.LSP (Liskov Substitution Principle)Is the cornerstone of inheritance reuse, only when the derived class can replace the base class, and the function of the software unit is not affected, the base class can be truly reused, and the derived class can add new behavior on the base class. Richter’s substitution principle is a complement to the open – close principle. Abstract is the key step to realize the open and close principle, and the inheritance relationship between base class and subclass is the concrete realization of abstraction, so the Richter substitution principle is the specification of the concrete steps to realize abstraction.
3. Dependency inversion Principle (Dependence Inversion Principle)
  • Programming for interfaces relies on abstraction rather than concrete.
4. Interface Isolation Principle (Interface Segregation Principle)
  • Using multiple isolated interfaces is better than using a single interface. Another implication is to reduce coupling between classes. Thus, in fact, design mode is a software design idea that starts from large-scale software architecture and is easy to upgrade and maintain. It emphasizes reducing dependence and coupling.
5. Demeter’s Rule, also known as the least Know Principle (Demeter Principle)
  • One entity should interact with other entities as little as possible so that the functional modules of the system are relatively independent.
6. Principle of composite reuse (Composite Reuse Principle)
  • Try to use composition/aggregation rather than inheritance.

The factory pattern

Introduction to the

  • Solution: interface selection problem (define an interface to create objects and let subclasses decide which factory class to instantiate).
  • Use: Explicitly plan to create different instances under different conditions.
  • How: Subclasses implement the factory interface and return an abstract product.
  • Scenario: Choose a teacher.

The advantages and disadvantages

  • Advantages:
    1. To create an object, you only need to know its name;
    2. High scalability, as long as a new product to extend a factory class;
    3. Mask the internal implementation and only care about the corresponding interface of the product.
  • Disadvantages:
    1. Each additional product requires the addition of a concrete class and object implementation factory, doubling the number of classes in the system and increasing the complexity of the system to a certain extent.

For example,

  • If you want to select a teacher for a subject, you just need to pass in the subject you want.
// teacher class teacher {teach() {return 'teacher '; Class extends Teacher {teach() {return 'Math'; }} class ChineseTeacher extends Teacher {teach() {return 'Chinese'; TeacherFactory {getTeacher(teacher) {if (teacher === 'math') {return MathTeacher(); } else if (teacher === 'chinese') { return new ChineseTeacher(); } return new Teacher(); } } function factoryDemo() { const teacherFactory = new TeacherFactory(); console.log('math', teacherFactory.getTeacher('math').teach()); console.log('chinese', teacherFactory.getTeacher('chinese').teach()); console.log('empty', teacherFactory.getTeacher('').teach()); } factoryDemo();Copy the code

Abstract Factory Pattern (Factory of factory)

Introduction to the

  • Like the factory pattern, it addresses the problem of interface selection (providing an interface that creates a series of related or interdependent objects without specifying their specific classes).
  • Usage: the products of the system have more than one product family, and the system only consumes the products of one of these family.
  • Approach: Define multiple products within a product family.
  • Scenario: Choose a teacher; The web,AppSuch as avi.

The advantages and disadvantages

  • Advantages: When multiple objects in a product family are designed to work together, it ensures that the client always uses only objects in the same product family.
  • Disadvantages: Product family extension is very difficult to add a certain product to a family, both in the abstractAbstractFactoryAdd code, and add code in the concrete inside.

For example,

  • For example, you can choose a teacher for a particular subject, or you can specify a male or female.
// Add the following code to the example code above to replace TeacherFactory and factoryDemo code // Gender class Sex {Sex () {return "; } } class ManSex extends Sex { sex() { return 'Man'; } } class WomanSex extends Sex { sex() { return 'Woman'; Class AbstractFactory {getTeacher(teacher) {return new teacher (); } getSex(sex) { return new Sex(); Class TeacherFactory extends AbstractFactory {getTeacher(teacher) {if (teacher === 'math') {return new MathTeacher(); } else if (teacher === 'chinese') { return new ChineseTeacher(); } return new Teacher(); } getSex(sex) { return new Sex(); Class SexFactory extends AbstractFactory {getTeacher(teacher) {return new teacher (); } getSex(sex) { if (sex === 'woman') { return new WomanSex(); } else if (sex === 'man') { return new ManSex(); } return new Sex(); Class FactoryProvider {getFactory(type) {if (type === 'teacher') {return new TeacherFactory()} else if (type === 'sex') { return new SexFactory() } } } function factoryDemo() { const factoryProvider = new FactoryProvider(); console.log('teacher: math ----', factoryProvider.getFactory('teacher').getTeacher('math').teach()); console.log('sex: woman ----', factoryProvider.getFactory('sex').getSex('woman').sex()); } factoryDemo();Copy the code

The singleton pattern

Introduction to the

  • Resolution: a globally used class is frequently created and destroyed. (Ensure that a class has only one instance and provide a global access point to access it.)
  • Use: when you want to control the number of instances and save system resources.
  • Method: Determine if the system already has this singleton, return it if it does, create it if it does not.
  • Scenario: The error popover on the page always remains one.

The advantages and disadvantages

  • Advantages:
    1. Having only one instance in memory reduces the overhead of memory, especially the frequent creation and destruction of instances (such as the management school homepage page cache).
    2. Avoid multiple resources (such as write file operations).
  • Disadvantages: No interface, no inheritance, conflicts with the single responsibility principle, a class should only care about internal logic, not how to instantiate outside.

implementation

class Singleton { constructor(name) { this.name = name; } getName() { return this.name; } static getInstance(name) {if (singleton.instance === undefined) {singleton.instance = new Singleton(name); } return Singleton.instance; }} // test const ins1 = singleton.getInstance (' singleton.getInstance '); const ins2 = Singleton.getInstance('17'); console.log('ins1 === ins2 ? ', ins1 === ins2); // ins1 === ins2 ? true console.log(ins1.name, ins2.getName()); // Little little seventeen little seventeenCopy the code

Builder model

Introduction to the

  • Solution: Faced with the creation of “a complex object”, which is usually composed of sub-objects of each part with a certain algorithm; The pieces of this complex object often face drastic changes due to changing requirements, but the algorithms that put them together are relatively stable. (Separating a complex build from its representation allows the same build process to create different representations.)
  • Use: When some basic components do not change and the combination often changes.
  • Method: Separate change from immutability.
  • Scenario: Objects that need to be generated have complex internal structures. The internal properties of the object that need to be generated are themselves interdependent. (e.g., ordering different meals, building houses)

The advantages and disadvantages

  • Advantages:
    1. The builder is independent and easy to expand.
    2. Easy to control risk details.
  • Disadvantages:
    1. Products must have something in common and be limited in scope.
    2. If the internal changes are complex, there will be many construction classes.

For example,

Class Worker {constructor(partName) {console.log(' Worker: I am building ', partName); this.partName = partName; Constructor () {console.log(' create project ');}} // Constructor () {console.log(' create project '); } build(partName) {console.log(' start building ', partName); } } class CreatePart extends Part { constructor(partName) { super(); this.partName = partName; } build() { super.build(this.partName); this.worker = new Worker(this.partName); } getResult() {console.log(this.partname, 'build done '); Return this. Worker}} // constructor {constructor(need) {this. Need = need; Console. log(' My build needs ', need); } start() {const WorkOver = this.need.map(element => {console.log(' view '${element}' drawing '); const builder = new CreatePart(element); builder.build(); return builder.getResult(); }); Console. log(' All built ', WorkOver); }} const develop = new Developer([' living ', 'living ']) develop. Start ();Copy the code

The prototype pattern

Introduction to the

  • Addresses creating and removing prototypes at run time. (Specify what kind of objects to create with prototype instances, and create new objects by copying these prototypes.)
  • Use:
    1. When a system should be created, constructed, and represented independently of its product.
    2. When the class to be instantiated is specified at run time, for example, by dynamic loading.
    3. To avoid creating a factory class hierarchy parallel to the product class hierarchy.
    4. When an instance of a class can have only one of several different combinations of states. It may be more convenient to create a proportionate number of prototypes and clone them than to manually instantiate the class each time in the appropriate state.
  • Method: Using an existing prototype object, quickly generate the same instance as the prototype object.
  • Scenarios: resource optimization, performance and security requirements, multiple modifiers for an object, and so on

The advantages and disadvantages

  • Advantages:
    1. Improved performance.
    2. Escape constructor constraints.
  • Disadvantages:
    1. Having a clone approach requires a thorough consideration of the functionality of a class, which is not difficult for a new class, but not always easy for an existing class, especially if a class reference does not support serialization of indirect objects, or if the reference has a circular structure.

implementation

Const prototype = {name: 'teeny teeny ', getName() {return this.name; Const xiao17 = object. create(prototype, {name: {value: '小17'}, parentName: { value() { return prototype.name } } }); console.log(xiao17.getName()); console.log(xiao17.parentName()); console.log(xiao17.__proto__ === prototype);Copy the code

conclusion

  • The creation pattern is characterized by the separation of object creation from usage. We only need to focus on the usage, the user does not need to focus on the object creation details, the object creation is done by the relevant factory. This reduces the coupling of the system.
  • In daily development, we can choose the corresponding design mode to deal with the corresponding problems by comparing different design modes with similar requirements, so as to reduce the coupling degree of code and improve the readability of code.

More quality articles

  • Behavior Patterns in JavaScript Design Patterns (Part 2)
  • Behavior Patterns in JavaScript Design Patterns (Part 1)
  • Structural patterns for JavaScript design patterns
  • Public account open small program best solution (Vue)
  • Webpack in-depth understanding of Loader
  • Common but overlooked approaches to ES6 (End game – Latest Proposal)
  • There’s always something you don’t know about avaScript Date objects?
  • Axios you probably don’t know how to use
  • Markdown to HTML is used in the project
  • Take a look at the most fully written implementation of ES6 Promise

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create a better article, thank 🙏 everyone.