js 设计模式 - 单例模式

设计模式 - 单例模式

在一些场景下,我们会碰到一些比较棘手的对象(如只允许出现一个弹窗,只允许有一个领导)等。这个时候就需要使用单例模式

var Dog = function(name) {
	this.name = name
	this._instance = null
}

Dog.createDog = function(newName) {
	if(this._instance){
		this._instance.name = newName
	}else{
		this._instance = new Dog(newName)
	}
	return this._instance
}	

let husky = Dog.createDog('husky')
let shiba = Dog.createDog('shiba')
console.log(husky.name) // shiba
console.log(shiba.name) // shiba
console.log(husky === shiba) // true

上面的案例就是单例模式的最简单模式

发布了1 篇原创文章 · 获赞 0 · 访问量 1

猜你喜欢

转载自blog.csdn.net/weixin_44053057/article/details/104768147