Preface
This article will give a brief overview of more than 20 JavaScript design patterns, and then write example code in combination with the ES6 class to show how it is used.
JavaScript plays an important role in modern front-end, and it is no longer on the same level as what it can be done in the past. The biggest feature of JavaScript is its flexibility. Generally, as long as you dare to think and write, you can write the program very simply and in a very complicated way. Its flexibility leads to continuous optimization and continuous questioning of the quality of writing when writing JavaScript. Design patterns are not divided into programming languages, but are the content of software engineering. JavaScript's powerful expressiveness gives developers creativity when writing code using design patterns.
Design Pattern Series Articles:
- ES6 Class Chat JavaScript Design Pattern Creation Pattern
What is a design pattern?
Design patterns are a solution to common problems in software design, which are easy to reuse and expressive.
In software engineering, design pattern is a solution proposed to various common (recurring) problems in software design. It is not used directly to complete the code writing, but rather to describe how to solve the problem in various situations. Object-oriented design patterns usually describe relationships and interactions in categories or objects, but do not involve specific categories or objects used to complete the application. —— Wikipedia
There are mainly reasons for using design patterns in JavaScript:
- Maintainability: Design pattern helps reduce the degree of coupling between modules.
- communicate: Design pattern provides a common set of terms for handling different types of objects.
- performance: Optimize the code and improve the running speed of the program. Of course not all design patterns can improve performance.
There are three modes:Creation mode, structural mode, behavior mode.
- Creation mode:Solve problems related to creating objects.
- Structural mode:Deal with relationships between entities and how they form a larger structure together.
- Behavioral pattern:Process how objects communicate and interact with each other.
Structural design pattern
Structural design patterns involve class and object combinations, using inheritance to combine interfaces.
In software engineering, structural design patterns are design patterns that simplify designs by identifying simple ways to realize relationships between entities.
- Adapter mode
- Bridge mode
- Combination mode
- Decorator mode
- Facade mode
- Enjoy the Yuan mode
- Agent Mode
Adapter mode
Adapter mode allows classes with incompatible interfaces to work together by encapsulating their own interfaces around existing classes. Adapters, also known as wrappers, are used to replace mismatched interfaces with one that can be used in existing systems.
In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with other classes without modifying their source code.
Example
The example will be modified with an example of a calculator.Calculator1
It's an old interface,Calculator2
It is the new interface. An adapter will be built that will wrap the new interface and provide it with results using its new method.
class Calculator1 { constructor() { = function (value1, value2, operation) { const operationHandler = { add: () => value1 + value2, sub: () => value1 - value2, }; return ( typeof (operationHandler[operation] === "function") && operationHandler[operation]() ); }; } } class Calculator2 { constructor() { = function (value1, value2) { return value1 + value2; }; = function (value1, value2) { return value1 - value2; }; } } // Build the class using adapter modeclass CalcAdapter { constructor() { const cal2 = new Calculator2(); = function (value1, value2, operation) { return ( typeof (cal2[operation] === "function") && cal2[operation](value1, value2) ); }; } } const adaptedCalc = new CalcAdapter(); ((30, 25, "sub")); // 5
Bridge mode
The bridge pattern separates the abstraction from the implementation so that the two can be changed independently. It is a method that can not only connect two objects together but also avoid strong coupling between the two.
A bridge pattern is a structured design pattern that allows a large class or a group of closely related classes to be split into two independent hierarchies: abstraction and implementation, which can be developed independently of each other. —— Wikipedia
Example
A renderer class is created to render multiple shapes.
class VectorRenderer { renderCircle(radius) { (`Render a radius of ${radius} The circle`); } } class RasterRenderer { renderCircle(radius) { (`Draw a radius of ${radius} Pixel circle`); } } class Shape { constructor(renderer) { = renderer; } } class Circle extends Shape { constructor(renderer, radius) { super(renderer); = radius; } draw() { (); } resize(factor) { *= factor; } } const raster = new RasterRenderer(); const vector = new VectorRenderer(); const circle = new Circle(vector, 5); const rasterCircle = new Circle(raster, 5); (); (2); (); (); (2); ();
Combination mode
Combination mode combines objects so that they can be operated as a single object, which is ideal for creating dynamic user interfaces on WEB.
Combination mode describes a set of objects that are processed in the same way as a single instance of an object of the same type. —— Wikipedia
Example
Working examples will be used:
class Employer { constructor(name, role) { = name; = role; } print() { const { name } = this; (`Name:${name}`); } } class EmplyerGroup { constructor(name, composite = []) { (name); = name; = composite; } print() { (); ((emp) => { (); }); } } const ravi = new Employer("ravi", "developer"); const bhavy = new Employer("bhavy", "developer"); const groupDevelopers = new EmplyerGroup("Developer", [ravi, bhavy]); ();
Decorator mode
The decorator pattern dynamically adds or overwrites the object's behavior, which is used to transparently wrap the object into another object with the same interface.
A decorator pattern is a design pattern that allows behavior to be dynamically added to a single object without affecting the behavior of other objects in the same class.
Example
The color and shape will be used as an example, if you have to draw a circle, you will create the method and draw a circle. If you want to draw a red circle, add the behavior to an object, the decorator pattern will help implement it.
class Shape { constructor(color = "") { = color; } } class Circle extends Shape { constructor(radius = 0) { super(); = radius; } resize(factor) { *= factor; } toString() { return `One diameter is ${} The garden`; } } class ColoredShape extends Shape { constructor(shape, color) { super(); = shape; = color; } toString() { return `${()},The color is${}`; } } const circle = new Circle(2); (circle); // Circle { color: '', radius: 2 } const redCircle = new ColoredShape(circle, "red"); (()); // One diameter is 2 The garden,The color is红色
Facade mode
Facade mode provides a simplified interface for complex code that can be used to convert existing interfaces into a more convenient interface.
Facade mode is a software design mode commonly used in object-oriented programming. Similar to the appearance in the architecture, the appearance is an object that acts as a current interface, masking more complex underlying or structural code. —— Wikipedia
Example
Take an example of a client interacting with a computer:
class CPU { freeze() { ("freeze…"); } jump() { ("jump over…"); } execute() { ("implement…"); } } class Memory { load(position, data) { ("loading…"); } } class HardDrive { read(lba, size) { ("Reading..."); } } class ComputerFacade { constructor() { = new CPU(); = new Memory(); = new HardDrive(); } start() { (); ("", ("lba", "size")); (""); (); } } const computer = new ComputerFacade(); ();
Enjoy the Yuan mode
The Encyclopedia pattern reduces the memory cost of creating similar objects and is a design pattern that can be used for optimization purposes. Best for solving the problem of performance plaguing by creating a large number of similar objects.
Xiangyuan is an object that minimizes memory usage by sharing as much data as possible with other similar objects. —— Wikipedia
Example
Taking the user as an example, let multiple users with the same name save memory by storing a name and referring it to users with the same name.
class User { constructor(fullname) { = fullname; } } class User2 { constructor(fullname) { const getOrAdd = (s) => { const idx = (s); if (idx !== -1) { return idx; } else { (s); return - 1; } }; = (" ").map(getOrAdd); } } = []; const getRadmon = (max) => (() * (max)); const randomString = () => { const result = []; for (let x = 0; x < 10; ++x) { ((65 + getRadmon(26))); } return (""); };
Memory size will now be compared by creating 10k users to perform occupancy character size without using the occupancy mode and using the occupancy mode.
const users = []; const users2 = []; const firstnames = []; const lastnames = []; for (let i = 0; i < 100; ++i) { (randomString()); (randomString()); } for (const first of firstnames) { for (const last of lastnames) { (new User(`${first} ${last}`)); (new User2(`${first} ${last}`)); } } (`10kThe user occupied about ${(users).length} character`); // 10k users occupy about 370001 charactersconst user2length = [users2, ] .map((x) => (x).length) .reduce((x, y) => x + y); (`10kUsers occupy a total of occupancy in the Xiangyuan mode ${user2length} character`); // 10kUsers occupy a total of occupancy in the Xiangyuan mode 191602 character
Agent Mode
By using a proxy, one class can represent the functionality of another class. For more detailed introduction, please refer to "JavaScript Design Pattern Agent Pattern》
Agent mode is a software design mode. Agent, in its most general form, is a class that serves as an interface to other things. —— Wikipedia
Example
Take value agents as examples.
class Percentage { constructor(percent) { = percent; } toString() { return `${}%`; } valueOf() { return / 100; } } const fivePercent = new Percentage(5); (()); // 5% (`5% of50Double yes${50 * fivePercent}`); // 5% of50Double yes2.5
This is the article about writing structured patterns in JavaScript design patterns in combination with ES6. For more related JS structured patterns, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!