单例设计模式介绍
所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类
只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
1.饿汉式写法
饿汉式(静态常量)
饿汉式(静态常量)应用实例
步骤如下:
1) 构造器私有化 (防止 new )
2) 类的内部创建对象
3) 向外暴露一个静态的公共方法。getInstance
4) 代码实现
//饿汉式写法(静态常量)
namespace Singleton {
class Singleton {
//1.构造器私有化,外部能new
private constructor() {
}
//2.本类内部创建对象实例
private static readonly instance = new Singleton();
//3.提供一个公有的静态方法,返回实例对象
static getInstance(): Singleton {
return Singleton.instance;
}
}
//测试
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
console.log('饿汉式写法(静态常量):', instance1 ==&