Welcome to my blog

introduce

The creation pattern is the pattern of creating objects, abstracting the process of instantiation. It helps a system be independent of how it creates, combines, and represents its objects. In other words, the process of creating an object is encapsulated, and the client only needs to use the object, and no longer cares about the logic in the process of creating the object.

The singleton pattern

There is only one instance of a class, whenever we want to ensure that only one object instance of that class exists.

This is often used in games, such as brick games, in the brick class and baffle class are used in the ball class. But the properties of the ball class are all changing, and the ball can only be a single instance. This is where the singleton pattern is needed

class Singleton {
    private constructor(){}private static instance: Singleton = new Singleton()
    public static getInstance(): Singleton {
        return this.instance
    }
}
Copy the code

Simple Factory model

A class that creates objects and encapsulates the instantiation of object behavior

This is often used in the game, for example, there are a variety of planes in the masturbation game, you can use factory mode to create the corresponding aircraft instance

interface Product { }

class Product1 implements Product { constructor(){}}class Product2 implements Product { constructor(){}}// Simple factory
class SimpleFactory {
    public static createProduct(type: number): Product {
        const mp = {
            1: new Product1(),
            2: new Product2()
        }
        return mp[type]}}// The factory pattern defines an abstract method for creating objects. Subclasses decide which classes to instantiate
abstract class AbstractFactory {
    public abstract createProduct(type: number): Product
}

class Factory extends AbstractFactory {
    constructor() {
        super()}public createProduct(type: number): Product {
        const mp = {
            1: new Product1(),
            2: new Product2()
        }
        return mp[type]}}Copy the code