[This is the sixth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.]

Design pattern is the basis of any good software, JavaScript is not exceptional also, learning design patterns, let you how some idea to code organization, learning through code snippet coding ideas for developers is relatively easy to understand, this article continues through simple code snippet shows the common design patterns, but not into design pattern itself, Here I recommend a book called “JavaScript Design Patterns”, which is easy to understand and can greatly improve your coding level after reading.

Constructor pattern

A Constructor Pattern is a function that initializes an object with specific properties and methods. The constructor pattern is similar to this definition. We use this pattern to create multiple instances of the same object.

function Article(title, author) { this.title = title; this.author = author; this.showTitle = () => console.log(this.title); } const article = new article ("JavaScript design mode ", "devpoint"); article.showTitle();Copy the code

The prototype pattern

A Prototype Pattern is an object creation Pattern in which new instances of objects are created by cloning objects from prototypes.

If you find that directly constructing a new object is complex and inefficient, then the prototype pattern is ideal for this situation.

function Article(title, author) { this.title = title; this.author = author; this.showTitle = () => console.log(this.title); } Article.prototype.showAuthor = function () { console.log(this.author); }; Const article = new article ("JavaScript Design mode ", "devpoint"); article.showAuthor();Copy the code

The factory pattern

The main idea of the Factory Pattern is to separate the creation of an object from its implementation, and its Pattern may be used during development without knowing it. In JavaScript, it separates object creation from the rest of the code, encapsulates the creation code, and exposes the API to generate different objects.

const Vehicle = function () {};
const Car = function () {
    this.say = function () {
        console.log("I am a car");
    };
};
const Truck = function () {
    this.say = function () {
        console.log("I am a truck");
    };
};
const Bike = function () {
    this.say = function () {
        console.log("I am a bike");
    };
};
const VehicleFactory = function () {
    this.createVehicle = (vehicleType) => {
        let vehicle;
        switch (vehicleType) {
            case "car":
                vehicle = new Car();
                break;
            case "truck":
                vehicle = new Truck();
                break;
            case "bike":
                vehicle = new Bike();
                break;
            default:
                vehicle = new Vehicle();
        }

        return vehicle;
    };
};
const vehicleFactory = new VehicleFactory();
const car = vehicleFactory.createVehicle("car");
const truck = vehicleFactory.createVehicle("truck");
const bike = vehicleFactory.createVehicle("bike");
car.say(); // I am a car
truck.say(); // I am a truck
bike.say(); // I am a bike
Copy the code

Command mode

The primary purpose of a Command Pattern is to encapsulate actions or operations as objects.

Suppose you need to build a payment system for e-commerce, and depending on the payment method you choose, you will need to handle specific processes.

If (selectedPayment == "creditcard") {// process creditcard payment}Copy the code

Some payment methods deal with only one step, but others may involve more than one step. By using the sample code above, you provide an implementation rather than an interface, which results in tight coupling.

The command pattern is a good solution to provide loose coupling. The system should not know too much about the processing of each particular payment method. To achieve this, the pattern separates the code that requests the action from the code that performs the actual implementation.

function Command(operation) { this.operation = operation; } Command.prototype.execute = function () { this.operation.execute(); }; Function CreditCardPayment() {return {execute: function () {console.log(" credit card "); }}; } function WechatPayment() {return {execute: function () {console.log(" WechatPayment "); }}; } function AliPayment() {return {execute: function () {console.log(" alipay "); }}; } function CreditCardCommand() { return new Command(new CreditCardPayment()); } function WechatPalCommand() { return new Command(new WechatPayment()); } function AliPayCommand() { return new Command(new AliPayment()); } function PaymentHelper() { let paymentCommand; return { setPaymentCommand: function (command) { paymentCommand = command; }, executeCommand: function () { paymentCommand.execute(); }}; } function run() { const paymentHelper = new PaymentHelper(); paymentHelper.setPaymentCommand(new CreditCardCommand()); paymentHelper.executeCommand(); paymentHelper.setPaymentCommand(new WechatPalCommand()); paymentHelper.executeCommand(); paymentHelper.setPaymentCommand(new AliPayCommand()); paymentHelper.executeCommand(); } run();Copy the code

Observer mode

The Observer Pattern, also known as the Publish/Subscribe Pattern, defines a one-to-many relationship in which multiple Observer objects listen to a topic object at the same time and notify all observers when the status of the topic object changes. So that they can update themselves automatically.

To illustrate the above concept, use the example of a daily journal subscription. Journal subscriptions involve two main roles: the journal publisher and the subscriber, and the relationship between them is as follows:

  • Periodical publisher – Responsible for the publication and distribution of periodicals
  • Subscribers – Simply subscribe to a new edition of the journal and will be notified when it is published. If you unsubscribe, you will not receive any further notifications.
function Newsletter() { this.observers = []; } Newsletter.prototype = { subscribe: function (observer) { this.observers.push(observer); }, unsubscribe: function (observer) { this.observers = this.observers.filter((ob) => ob ! == observer); }, notify: function () {this.observers.foreach ((observer) => console.log(" Hello! + observer.toString()) ); }}; Const subscriber1 = "subscriber1 "; Const subscriber2 = "subscriber2 "; const newsletter = new Newsletter(); newsletter.subscribe(subscriber1); newsletter.subscribe(subscriber2); newsletter.notify(); // Output: Hello! Subscriber 1; Hello! Unsubscribe (subscriber2); newsletter.notify(); / / hello! The subscriber 1Copy the code

A singleton

Singleton patterns are one of the most basic yet most useful patterns in JavaScript, and are more commonly used than any other Pattern. This pattern provides a way to organize code into a logical unit that can be used to reduce the number of global variables.

const utils = (function () { let instance; function initialize() { return { sum: function (a, b) { return a + b; }}; } return { getInstance: function () { if (! instance) { instance = initialize(); } return instance; }}; }) (); const sum = utils.getInstance().sum(1, 2); console.log(sum); / / 3Copy the code

The main benefit of the monomer pattern is its ability to organize code by grouping related methods and attributes in a single unit that will not be instantiated multiple times, making debugging and maintenance easier, but leading to strong coupling between modules.

The module pattern

A Module Pattern, also known as a monomer Pattern, is a design Pattern used to implement the concept of a software Module. Functions, variables, and properties within a Module can be set as public or private members.

Const articleModule = (function () {// private const title = "JavaScript Design mode "; // Public return {printTitle: function () {console.log(title); }}; }) (); articleModule.printTitle(); // JavaScript design patternCopy the code

conclusion

The above are just some simple examples of design patterns, to have a preliminary understanding of them, you can try to use the above examples to write code during the development process, to improve the quality of coding is a certain help.