Skip to content

设计模式的种类

  1. 创建型模式:创建类实例对象的方式
    1. 单例
    2. 工厂
    3. 抽象工厂
    4. 原型
    5. 建造者
  2. 结构型模式:类或对象有机结合形成一种复合型的对象解构
    1. 适配器
    2. 装饰器
    3. 桥接
    4. 外观
    5. 享元
    6. 代理
    7. 组合
  3. 行为型模式:对象之间的交互方式
    1. 模板
    2. 命令
    3. 状态
    4. 访问者
    5. 观察者
    6. 迭代器
    7. 备忘录
    8. 中介着
    9. 解释器
    10. 策略
    11. 职责链

单例模式 Singleton pattern

  • 定义:一个类只有一个实例
  • 创建要求:
    • 类中有一个静态创建唯一实例的方法(不可以使用new创建对象)
    • 构造方法私有化
    • 类只能通过静态方法的执行进行创建并放回唯一实例

饿汉模式

ts
class User {
    private static instance: User = new User()

    private constructor() {}

    public static getInstance() {
        return User.instance
    }
}
const user1 = User.getInstance()
const user2 = User.getInstance()
console.log(user1 === user2) // true

user装载的时候就会创建实例,不用也会占用内存

懒汉模式

ts
class User {
    private static instance: User

    private constructor() {}

    public static getInstance() {
        if (User.instance === null) {
            User.instance = new User()
        }
        return User.instance
    }
}
const user1 = User.getInstance()
const user2 = User.getInstance()
console.log(user1 === user2) // true

user装载的时候不会创建实例,使用的时候在进行创建

工厂模式

简单工厂

  • 核心理论:设计模式的核心操作是去观察你整个逻辑里面的“变与不变”,然后将变与不变分离,达到使变化的部分灵活、不变的地方稳定的目的
js
// 定义产品类
class ProductA {
    constructor() {
        this.name = 'ProductA'
    }

    display() {
        console.log(`This is ${this.name}`)
    }
}

class ProductB {
    constructor() {
        this.name = 'ProductB'
    }

    display() {
        console.log(`This is ${this.name}`)
    }
}

// 工厂类
class SimpleFactory {
    createProduct(type) {
        switch (type) {
            case 'A':
                return new ProductA()
            case 'B':
                return new ProductB()
            default:
                throw new Error('Unknown product type')
        }
    }
}

// 使用工厂创建产品
const factory = new SimpleFactory()

const productA = factory.createProduct('A')
productA.display() // 输出: This is ProductA

const productB = factory.createProduct('B')
productB.display() // 输出: This is ProductB

ProductA 和 ProductB 是两个不同的产品类,每个类都有自己的属性和方法 SimpleFactory 是一个工厂类,包含一个 createProduct 方法,根据传入的产品类型返回相应的产品实例 通过创建 SimpleFactory 的实例,可以使用 createProduct 方法来创建所需类型的产品对象

抽象工厂

单例模式

  • 定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点,这样就叫做单例模式
js
class Singleton {
    constructor(options) {
        // 初始化配置项
        this.initOptions(options)

        // 初始化创建单例
        return this.createSingleton(options)
    }

    createSingleton(options) {
        // 保存this指向
        const _this = this
        const instance = _this.constructor._instance

        // 如果你这样写的话,你的实例对象属性并不会再次的初始化
        // if (!instance) _this.createInstance();

        //如果你这样写的话,你就可以让实例对象属性重新进行初始化
        !instance ? _this.createInstance() : _this.initOptions.call(Singleton._instance, options)

        return _this.getInstance()
    }

    getInstance() {
        const _this = this
        return _this.constructor._instance
    }

    createInstance() {
        const _this = this
        Object.defineProperty(Singleton, '_instance', {
            enumerable: true,
            writable: false,
            configurable: false,
            value: _this
        })
    }

    initOptions(options) {
        // 初始化配置项
        const { name = '聪', age = 25, hobby = [] } = options
        this.name = name
        this.age = age
        this.hobby = hobby
    }
}

const s1 = new Singleton({
    name: 'lengran',
    age: 26,
    hobby: ['摸鱼🐟', '逛公园⛲️']
})
const s2 = new Singleton({
    name: 'lengran',
    age: 25,
    hobby: ['恋爱❤️', '唱歌👅']
})

console.log('s1 ==== s2', s1 === s2) // true

本质上就是让Singleton构造函数具有判断自己是否已经创建过一个实例对象 如果已经创建过,那么就返回之前创建的实例对象,否则就创建一个新的实例对象并返回。 这样就保证了,无论你创建多少个Singleton实例对象,实际上只有一个实例对象会被创建出来,并且这个实例对象是唯一的。