理解设计模式(六)——单例模式

单例模式

理解设计模式(一)——简单工厂 理解设计模式(二)——工厂方法 理解设计模式(四)——建造者 理解设计模式(五)——原型模式

提出问题

有时候,我们全局只需要一个对象。在不同的地方使用只是引用同一个对象。比如单例模式可以和工厂模式一起使用,因为我们往往只需要一个工厂。

解决问题

如何实现单例模式呢?

其实单例模式实现方式有很多种,重点是要领会思想。即全局只有一个对象。创建对象时,如果没有创建过,则新建一个并保存这个对象。如果已经创建过,则返回已有的对象。

下面是一种实现方法:

class Singleton {
constructor() {
this.instance = null;
}

getInstance() {
if(!this.instance)
this.instance = new Obj();
return this.instance;
}
}

这种实现具有懒创建的特性。也就是说,只有当调用getInstance方法时才真正创建了对象。

结合工厂模式

class SimpleFactory {
constructor() {
this.objs = {};
}
getInstance(type) {
if(type==="type1") {
return this.objs["type1"]||this.objs["type1"]=new Type1();
}
if(type==="type2") {
return this.objs["type2"]||this.objs["type2"]=new Type2();
}
}
}
Author: LeoB_O
Link: https://leob-o.github.io/2019/06/04/SingletonPattern/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.