JavaScript design pattern (1)-singleton mode

  The definition of singleton mode is to ensure that a "class" has only one instance and provide a global access point to access it. 

  The class of the singleton mode is a variable that only needs to be created once (this does not mean that it cannot be changed after it is created), so we need a general method to determine whether a class has been created, just pass a Lock to determine whether this class has been created. Therefore, we first introduce a general singleton pattern creation method, the code is as follows:

<script type="text/javascript">
	// 我们把业务逻辑封装在fn里通过变量的形式传入
	function createSingle(fn){
		let lock = null
		// 我们用闭包把lock保存下来
		return function(){
			return lock || lock = fn.apply(this,arguments)
		}
	}
</script>

  When we need a unique object, we write a function to create the object ourselves and hand it over to the singleton mode

var createObj = function(a,b){
	return {
		a:a,
		b:b
	}
}
let singleObj = createSingle(createObj) //生成单例模式
console.log(singleObj('aaa','bbb')) //{a:'aaa',b:'bbb'}
console.log(singleObj('ccc','ddd')) //{a:'aaa',b:'bbb'}

  We often use singleton mode in JavaScript, but we didn’t notice it. For example, if you create a variable a, and then you don’t recreate a variable in the code behind, we can think of a as a singleton mode, but We won't say it like that, so when I say that learning design patterns is to give your code a name, there is no soft use in fact.

Guess you like

Origin blog.csdn.net/dkr380205984/article/details/108601791