js design pattern - the use of singleton pattern
This time I will bring you the js design pattern-The use of singleton mode, the use of js singleton modeWhat are the precautions, The following is a practical case, let’s take a look.
1. Concept:
In the eyes of traditional development engineers, the single-interest model ensures that each class has only one instance. When implementing, we first determine whether the instance exists. If it exists, return it directly. If it does not exist, create it and return it. This ensures that there is only one instance object for each class. In JavaScript, a singleton serves as a provider of a namespace, providing a unique access point to access objects globally. 123
2. Functions and precautions:
Function: 1. Inter-module communication
2. Only one object of a certain class can exist in the system
3. Protect your own attributes and Method
Notes: 1. Pay attention to the use of this
2. Closures can easily cause memory leaks
3. Pay attention to the use of new when using inheritance.
3. The simplest way to implement
is to use object literals, which can contain a large number of properties and methods.
var firstObject = { property1: "something", property2: "something else", method1: function () { console.log('hello web!'); } };
If you want to extend this object, we can provide our own private members, and then we encapsulate these variable and function declarations inside it through closures. We can implement private or public methods. Let's look at the following code again:
var firstObject= function () { /* 这里声明私有变量和方法 */ var privateVariable = 'something private'; function showPrivate() { console.log(privateVariable); } /* 公有变量和方法(可以访问私有变量和方法) */ return { publicMethod: function () { showPrivate(); }, publicVar: 'the public can see this!' }; };var single = firstObject(); single.publicMethod(); // 输出 'something private'console.log(single.publicVar); // 输出 'the public can see this!'
If we want to initialize it only when it is used, how should we do it? In order to save resources, we can initialize these codes in another constructor, as follows:
var firstjObiect= (function () { var instantiated; function init() { /*这里定义单例代码*/ return { publicMethod: function () { console.log('hello world'); }, publicProperty: 'test' }; } return { getInstance: function () { if (!instantiated) { instantiated = init(); } return instantiated; } }; })();/*调用公有的方法来获取实例:*/firstjObiect.getInstance().publicMethod();
Let’s take a look at its usage scenarios. Singletons are generally used between systems. Communication coordination of various modes
var firstObjectTester = (function () { //参数:传递给单例的一个参数集合 function Singleton(args) { //设置args变量为接收的参数或者为空(如果没有提供的话) var args = args || {}; //设置name参数 this.name = 'SingletonTester'; //设置pointX的值 this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值 //设置pointY的值 this.pointY = args.pointY || 10; } //实例容器 var instance; var _static = { name: 'SingletonTester', //获取实例的方法 //返回Singleton的实例 getInstance: function (args) { if (instance === undefined) { instance = new Singleton(args); } return instance; } }; return _static; })();var singletonTest = firstObjectTester .getInstance({ pointX: 5 }); console.log(singletonTest.pointX); // 输出 5
Here is a link to an example of singleton mode implementation. Here is the link:
Solve the problem of converting Html to Txt and displaying Textarea data Txt to Html
The above method is mainly implemented, and there are other implementation methods (from Uncle Tom’s blog)
Method 1,
function Universe() { // 判断是否存在实例 if (typeof Universe.instance === 'object') { return Universe.instance; } // 其它内容 this.start_time = 0; this.bang = "Big"; // 缓存 Universe.instance = this; // 隐式返回this}// 测试var uni = new Universe();var uni2 = new Universe(); console.log(uni === uni2); // true
Method 2,
function Universe() { // 缓存的实例 var instance = this; // 其它内容 this.start_time = 0; this.bang = "Big"; // 重写构造函数 Universe = function () { return instance; }; }// 测试var uni = new Universe();var uni2 = new Universe(); uni.bang = "123"; console.log(uni === uni2); // trueconsole.log(uni2.bang); // 123
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
In-depth JavaScript DOM application
In-depth basic application of JavaScript
The above is the detailed content of js design pattern - the use of singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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.

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.
