又被称为单体模式,只允许实例化一次的对象类。有时也可以用一个对象来规划一个命名空间,井井有条地管理对象上的属性和方法。
单例模式应该是JavaScript中最常见的一种设计模式了,经常为我们提供一个命名空间,来防止不同的人命名变量的冲突,还可以用它来创建一个小型的代码库。
var MyTools = { elem: { getElement: function() {}, setElement: function() {} }, arr: { getArrLength: function() {}, updateArr: function() {} }, cookie: { getCookie: function() {}, removeCookie: function() {} } ... } //调用 MyTools.cookie.getCookie();
使用一个变量来标志当前是否已经为某个类创建过对象,如果创建了,则在下一次获取该类的实例时,直接返回之前创建的对象,否则就创建一个对象。
export function getPermissionObj() { if (!permissionObj){ permissionObj = new Permission() } return permissionObj; }
class Singleton { constructor(name) { this.name = name this.instance = null } getName() { alert(this.name) } static getInstance(name) { if (!this.instance) { this.instance = new Singleton(name) } return this.instance } } const instanceA = Singleton.getInstance('seven1') const instanceB = Singleton.getInstance('seven2') console.log(instanceA, instanceB)