设计模式与前端:优缺点以及使用场景(三)| 青训营

64 阅读2分钟

1:单例模式

单例模式(Singleton Pattern)是 最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供了一个全局访问点来访问该实例。

注意:

1、单例类只能有一个实例。

2、单例类必须自己创建自己的唯一实例。

3、单例类必须给所有其他对象提供这一实例。

单例模式的实现方式也有很多如饿汉模式、懒汉模式、双重检查锁(Double-Checked Locking)模式、静态内部类(Static Inner Class)模式、枚举(Enum)模式。

这里只介绍最常见的恶汉模式和懒汉模式

1:懒汉模式(LazyMan)

class Hungry {
    // 类加载时不初始化实例
    static HUNGRY = null;

    // 构造器保证外部无法创建实例,保证唯一
    constructor() {
        // 防止通过 new 关键字创建实例
        if (Hungry.HUNGRY) {
            throw new Error("Cannot instantiate the private constructor.");
        }
    }

    // 公开静态方法返回对象实例给所有其他对象访问
    // 第一次调用时才创建实例
    static getInstance() {
        if (!Hungry.HUNGRY) {
            Hungry.HUNGRY = new Hungry();
        }
        return Hungry.HUNGRY;
    }
}

// 使用示例
const instance1 = Hungry.getInstance();
const instance2 = Hungry.getInstance();

console.log(instance1 === instance2); // true,两个实例相同

2:饿汉模式(Hungry)

class Hungry {
    // 类加载时就初始化,浪费内存
    // 一来就自己给自己创建一个实例
    static HUNGRY = new Hungry();

    // 构造器保证外部无法创建实例,保证唯一
    constructor() {
        // 防止通过 new 关键字创建实例
        if (Hungry.HUNGRY) {
            throw new Error("Cannot instantiate the private constructor.");
        }
    }

    // 公开静态方法返回对象实例给所有其他对象访问
    static getInstance() {
        return Hungry.HUNGRY;
    }
}

// 使用示例
const instance1 = Hungry.getInstance();
const instance2 = Hungry.getInstance();

console.log(instance1 === instance2); // true,两个实例相同

优点:

1、在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例。

2、避免对资源的多重占用(比如写文件操作)。

缺点:

没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。