What is the singleton pattern

The singleton pattern is defined to guarantee only one instance of a class and to provide a global point of access to it.

For some objects, such as thread pools/global caches/window objects in browsers, we only need one instance. The following describes actual scenarios.

Ii. Actual scenario

1. Log in to the float window

When we click the login button, a login float window appears in the page. The login float window is unique and will only be created once, no matter how many times we click the login button. Therefore, this login float window is suitable for the singleton pattern.

1.1 Traditional Practices

Traditionally, when the page is loaded, the login float window is created. When the user clicks the login button, the login float window is displayed. The implementation code is as follows:

<! DOCTYPEhtml>
<html>
<head>
	<title></title>
</head>
<body>
  
	<button id="loginBtn">The login</button>
	<script type="text/javascript" src="index.js">
		
	</script></body></html>
Copy the code
var loginLayer = (() = > {
	let div = document.createElement('div')
	div.innerHTML = 'I'm logged in popover'
	div.style.display = 'none'

	document.body.appendChild(div)

	return div
})()

document.getElementById('loginBtn').onclick = () = > {
	loginLayer.style.display = 'block'
}

Copy the code

The source address

The above code has the following disadvantages:

  1. If you do not need to log in, a login float window is addedDOMNodes, waste performance.

Now optimize the code to add the DOM node for logging into the float window only after the user clicks the login button.

The code is as follows:

var createLoginLayer = () = > {
	let div = document.createElement('div')
	div.innerHTML = 'I'm logged in popover'
	div.style.display = 'none'

	document.body.appendChild(div)

	return div
}

document.getElementById('loginBtn').onclick = () = > {
	const loginLayer = createLoginLayer()
	loginLayer.style.display = 'block'
}

Copy the code

The source address

The above code also has flaws, as follows:

  1. Each time you click the login button, a login float window is created, frequentlyDOMNodes waste performance more.

In fact, we only need to create the login float window once.

1.2 Singleton mode

Refactor the above code through the singleton pattern.

const createLoginLayer = () = > {
	const div = document.createElement('div')
	div.innerHTML = 'I'm logged in popover'
	div.style.display = 'none'
	console.log(123)

	document.body.appendChild(div)
	return div
}

const createSingle = (function () {
	var instance = {}
	return function (fn) {
		if(! instance[fn.name]) { instance[fn.name] = fn.apply(this.arguments)}return instance[fn.name]
	}
})()

const createIframe = function () {
	const iframe = document.createElement('iframe')
	document.body.appendChild(iframe)
	iframe.style.display = 'none'
	return iframe
}

const createSingleLoginLayer = createSingle(createLoginLayer)
const createSingleIframe = createSingle(createIframe)

document.getElementById('loginBtn').onclick = () = > {
	const loginLayer = createSingleLoginLayer
	const iframe = createSingleIframe
	loginLayer.style.display = 'block'
	iframe.style.display = 'block'
}

Copy the code

The source address

After refactoring, the code was optimized as follows:

  1. Instance objects are createdcreateLoginLayer / createIframeAnd manages singleton objectscreateSingleIn line with the principle of single responsibility;
  2. Using closures to store instances and determine that no matter how many times the login button is clicked, only one login float window instance is created;
  3. Easy to extend, the next time you need to create a unique pageiframe / scriptAnd other labels, you can reuse the logic directly.

Third, summary

The singleton pattern is a simple but very useful pattern, especially the lazy singleton technique, where objects are created when appropriate and only one is created. Even more intriguingly, the responsibility for creating objects and managing singletons is distributed in two different methods that combine to have the power of the singleton pattern.


· Past wonderful ·

Design Patterns – Who hasn’t seen a few singletons (1)

Design Mode – What is happy Planet, What is Strategic Mode (part 2)

Design Mode – This is the Agent mode (3)

Design Patterns — Simple observer Patterns (part 4)

Design Mode – No, no, no, no, no, no, no, no.