


In-depth understanding of JavaScript series (25): Detailed explanation of the singleton pattern of design patterns_Basic knowledge
Introduction
Starting from this chapter, we will gradually introduce the implementation of various design patterns used in JavaScript. Here I will not introduce too much about the theory of the pattern itself, but will only focus on the implementation. OK, it’s officially started.
In the eyes of traditional development engineers, a singleton is to ensure that a class has only one instance. The implementation method is generally to first determine whether the instance exists. If it exists, return it directly. If it does not exist, create it and return it. This ensures A class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique access point to the object from the global namespace.
Text
In JavaScript, there are many ways to implement singletons. One of the simplest ways is to use object literals, which can contain a large number of properties and methods:
var mySingleton = {
Property1: "something",
Property2: "something else",
Method1: function () {
console.log('hello world');
}
};
If you later extend this object, you can add your own private members and methods, and then use closures to encapsulate these variable and function declarations inside it. Expose only the public members and methods you want to expose. The sample code is as follows:
var mySingleton = function () {
/* Declare private variables and methods here */
var privateVariable = 'something private';
Function showPrivate() {
console.log(privateVariable);
}
/* Public variables and methods (private variables and methods can be accessed) */
Return {
publicMethod: function () {
showPrivate();
},
publicVar: 'the public can see this!'
};
};
var single = mySingleton();
single.publicMethod(); // Output 'something private'
console.log(single.publicVar); // Output 'the public can see this!'
The above code is very good, but what if we want to initialize it only when it is used? In order to save resources, we can initialize these codes in another constructor, as follows:
var Singleton = (function () {
var instantiated;
Function init() {
/*Define singleton code here*/
return {
publicMethod: function () {
console.log('hello world');
},
publicProperty: 'test'
};
}
return {
getInstance: function () {
if (!instantiated) {
instantiated = init();
}
return instantiated;
}
};
})();
/*Call public methods to get instances:*/
Singleton.getInstance().publicMethod();
We now know how to implement a singleton, but in what scenarios is a singleton best used? In fact, singletons are generally used to coordinate various modes of communication between systems. The following code is a best practice for a singleton:
var SingletonTester = (function () {
//Parameters: a set of parameters passed to the singleton
Function Singleton(args) {
//Set the args variable to the received parameters or empty (if not provided)
var args = args || {};
//Set the name parameter
This.name = 'SingletonTester';
//Set the value of pointX
This.pointX = args.pointX || 6; //Get it from the received parameters, or set it to the default value
//Set the value of pointY
This.pointY = args.pointY || 10;
}
//Instance container
var instance;
var _static = {
name: 'SingletonTester',
//Method to get the instance
//Return Singleton instance
getInstance: function (args) {
If (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
Return _static;
})();
var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // Output 5
Other implementation methods
Method 1:
function Universe() {
// Determine whether an instance exists
If (typeof Universe.instance === 'object') {
return Universe.instance;
}
// Other content
This.start_time = 0;
This.bang = "Big";
// Cache
Universe.instance = this;
// Implicitly returns this
}
//Test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
Method 2:
function Universe() {
// cached instance
var instance = this;
// Other content
This.start_time = 0;
This.bang = "Big";
// Override constructor
Universe = function () {
return instance;
};
}
//Test
var uni = new Universe();
var uni2 = new Universe();
uni.bang = "123";
console.log(uni === uni2); // true
console.log(uni2.bang); // 123
Method 3:
function Universe() {
// Cache instance
var instance;
// Reconstructor function
Universe = function Universe() {
return instance;
};
// Post-processing prototype properties
Universe.prototype = this;
// Example
Instance = new Universe();
// Reset constructor pointer
Instance.constructor = Universe;
// Other functions
Instance.start_time = 0;
Instance.bang = "Big";
return instance;
}
// Test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
//Add prototype attributes
Universe.prototype.nothing = true;
var uni = new Universe();
Universe.prototype.everything = true;
var uni2 = new Universe();
console.log(uni.nothing); // true
console.log(uni2.nothing); // true
console.log(uni.everything); // true
console.log(uni2.everything); // true
console.log(uni.constructor === Universe); // true
Method 4:
var Universe;
(function () {
var instance;
Universe = function Universe() {
if (instance) {
return instance;
}
instance = this;
// Other content
This.start_time = 0;
This.bang = "Big";
};
} ());
//Test code
var a = new Universe();
var b = new Universe();
alert(a === b); // true
a.bang = "123";
alert(b.bang); // 123

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.
