You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
651 B
32 lines
651 B
4 years ago
|
/**
|
||
|
* 饿汉模式
|
||
|
* 特点:类加载时就初始化。
|
||
|
*/
|
||
|
class SingletonMode1 {
|
||
|
|
||
|
private static instance = new SingletonMode1()
|
||
|
|
||
|
// 将 constructor 设为私有属性,防止 new 调用
|
||
|
private constructor() { }
|
||
|
|
||
|
static getInstance(): SingletonMode1 {
|
||
|
return this.instance
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 懒汉模式
|
||
|
* 特点:需要时才创建对象实例。
|
||
|
*/
|
||
|
class SingletonMode2 {
|
||
|
private static instance: SingletonMode2
|
||
|
|
||
|
private constructor() { }
|
||
|
|
||
|
static getInstance(): SingletonMode2 {
|
||
|
if (!this.instance) {
|
||
|
this.instance = new SingletonMode2()
|
||
|
}
|
||
|
return this.instance
|
||
|
}
|
||
|
}
|