单例模式是针对类的一种设计,让类只能有一个实例对象,对于一些没必要产生第二个实例的类来说建议设计成单例类。
单例类的实例化过程是由自身实现的,减少了其他人使用该类时的心智负担。缺点是单例类由于静态属性,无法扩展。
由于单例类的实例化过程是由自身实现的,所以设计的时候在new这里就会产生两种方法。
1. 预加载单例
/**
*Singleton_quick
*
* @export
* @class Singleton_quick
*/
export class Singleton_quick {
private constructor() {}
public static instance: Singleton_quick = new Singleton_quick()
private _name: string
set name(value: string) {
this._name = value
}
get name(): string {
return this._name
}
}
程序刚开始运行,类就实例化完毕。减轻后续大量类实例化时产生的压力,提高运行流畅度。缺点是如果类比较庞大时,会使程序启动暂时阻塞,而且容易造成资源浪费,因为有些类可能并没有被调用。
2. 懒加载单例
/**
*Singleton_lazy
*
* @export
* @class Singleton_lazy
*/
export class Singleton_lazy {
private constructor() {}
private static instance: Singleton_lazy = null
public static getInstance(): Singleton_lazy {
this.instance = this.instance || new Singleton_lazy()
return this.instance
}
private _name: string
set name(value: string) {
this._name = value
}
get name(): string {
return this._name
}
}
类内部实现了一个getInstance方法,程序刚开始运行,类并不实例化,直到外部调用getInstance方法时才会执行构造函数,即用的时候再实例化对象。这样做可以避免程序启动刚开始时阻塞,类的所有资源采取懒加载策略。缺点是在多线程情况下会误判instance为null,然而js为单线程,不会涉及这方面的问题。
单例类的关键:
构造函数的访问权限为private。
静态实例。