Single-piece mode description
1. Description: Single-piece mode is an object that has been instantiated in static access. This object can only be accessed through a unique entrance, an object that has been instanced or to be instantiated; in server-side dynamic languages such as Java and .Net C#, it can ensure that class operations are carried out smoothly and avoid parallel operations causing confusion in data;
2. Benefits of single-piece mode:
1>. Reduce new operations to avoid speeding up frequent memory operations and occupying memory;
2>. Minimize the overhead of objects in large systems;
3>. As mentioned above, it can ensure that certain types of operations have accurate sequences and operations to avoid data abnormalities caused by parallel processing;
Of course, the benefits mentioned above are all in the server language. In a weak language like JavaScript, don’t worry so much, because the scripts are operated on your own client, and there is no problem of operation conflicts; it is equivalent to using the entire server alone, so don’t worry about who will operate your data;
Instance source code
var Singleton = {
instance: null,
MailSender: function() {
var self = this;
= '';
= '';
= '';
= function() {
//send body
}
},
getInstance : function() {
if ( == null) {
= new ();
}
return ;
}
}
How to use:
var mail = ();
= 'toname#';
= 'Single-piece mode send';
= 'Send content';
();
When some global frameworks, such as rich UI frameworks like DWZ, create a global Singleton, and there is no need to create them again;
Of course, if it is written like this, it will be more clear, and it will be the same as the server language:
().to = 'toname#';
().title = 'Single-piece mode send';
().content = 'Send content';
().send();
Other actual instructions
Where is the single-piece mode more useful? For example, when there is a unified configuration file on an operation server, such as large-scale concurrent operations, you need to pay attention to the situation where first comes and then arrives, such as the operation process records of the exchange, etc., you can all operate in single-piece mode;
Also: Single-piece mode method:
1. The way above is called lazy
2. How to Hungry Sticks:
var Singleton = {
instance : new (),
MailSender : function() {
var self = this;
= '';
= '';
= '';
= function() {
//send body
}
},
getInstance : function() {
return ;
}
}
The same way to use;
Use closure to create a single-piece pattern and hide the instance object
1. Code:
var Singleton = (function() {
var instance = null;
function MailSender() {
= '';
= '';
= '';
}
= function() {
//send body
}
return {
getInstance : function() {
if (instance == null) {
instance = new MailSender();
}
return instance;
}
}
})();
2. How to use:
//Same usage
var mail = ();
= 'toname#';
= 'Closed single-piece mode send';
= 'Send content';
();