First, the use of popular language to explain its meaning: from the Qin Shihuang established the emperor's position, and the same period only one. So you don't need to prefix the emperor with other prefixes when you call them. This process is reflected in the design field, which requires that a class can generate only one object, and that all objects have the same dependency on him, because there is only one object, so the object has the same dependency on him because there is only one object that everyone knows about. The emperor has to deal with a lot of things every day, but the emperor only one, that is, a class has only one object, object generation through the New keyword completion, we can use the constructor to control, because the new keyword is used to create an object based on the input parameters call the corresponding constructor, So if we set the access permission of the constructor to private, we can create the object outside of the binary.
Set the above scenario as a simple example:
Emperor Class:
1 Public classemperor{2 Private Static FinalEmperor emperor=NewEmperor ();//Initialize an emperor3 PrivateEmperor () {4 }5 Public StaticEmperor getinstance () {6 returnEmperor;7 }8 Public Static voidsay () {9System.out.println ("My is the Emperor");Ten } One}
By defining the constructor of the private access permission to avoid being a new object by another class, Emperor can handle the new object, and other classes can access getinstance to get the same object.
Minister class:
1 public class minister{ 2 public static void Main (String[]args) { 3 for (int day=0;day<3;day++) { 4 Emperor emperor=emperor.getinstance ( ); 5 emperor.say (); 6 7 8 }
Second, the definition of the singleton pattern
Singleton mode (Singleton pattern): Ensure class has a single instance,and provide a global point of access to it.
The Singleton class is called a singleton class by using the private constructor to ensure that only one instance is produced in an application. and is instantiated by itself (using new Singleton in Singleton).
Generic code for a singleton pattern:
1 Public classsingleton{2 Private Static FinalSingleton singleton=NewSingleton ();3 PrivateSingleton () {}4 Public StaticSingleton Getsingleton () {5 returnSingleton;6 }7 Public Static voiddosomething () {}8}
Application of single case model
1. Advantages of single-case mode
Because Singleton mode has only one instance in memory, reducing memory overhead, especially when an object needs to be created and destroyed frequently, and the performance of creation or destruction is not optimized, the advantages of the singleton pattern are obvious.
Because the singleton pattern generates only one instance, it reduces the performance overhead of the system, and when an object is generated that requires more resources, such as reading the configuration and generating other dependent objects, it can be resolved by producing a singleton object directly at application startup and then permanently residing the memory.
Singleton mode avoids multiple uses of resources, such as a write file action, because only one instance exists in memory and avoids simultaneous write operations on the same resource file.
Singleton mode can be used to set global access points, optimize and share resource access, for example, you can design a singleton class, responsible for all data table mapping processing.
2. Disadvantages of the Singleton model
The singleton mode generally has no interface, it is difficult to extend, but there is no second way to extend it. Why can't I add an interface to a singleton mode? Because the interface does not make any sense to the singleton pattern, he requires that he instantiate it himself and provide a single instance. An interface or abstract class cannot be instantiated.
The singleton mode is detrimental to the test and cannot be tested until the singleton mode is complete.
The singleton pattern is in conflict with the single responsibility principle, and a class should only implement one logic, not whether she is a singleton or not, and if the singleton is dependent on the environment, the singleton pattern will combine the singleton and the business logic in a single class.
3, the use of single-case mode of the scene
An environment that requires a unique serial number to be generated;
A shared access point or shared data, such as a counter on a Web page, can be used throughout the project, without having to log each refresh to the database, using a singleton pattern to burst the value of the guard and ensuring thread safety.
Creating an object consumes too much resources, such as accessing resources such as IO and databases
You need to define a number of static constants and static methods, such as tool classes.
4. Precautions for single-case mode
In case of high concurrency, note the problem of thread synchronization in singleton mode
Thread insecure single-case:
1 Public classsingleton{2 Public StaticSingleton singleton=NULL;3 PrivateSingleton () {}4 Public StaticSingleton Getsingleton () {5 if(singleton==NULL){6singleton=NewSingleton ();7 }8 returnSingleton;9 }Ten}
The singleton pattern is not problematic in low concurrency, and when concurrency increases, multiple instances of memory may exist, destroying the initial expectations. For example, thread a executes to singleton=new Singleton () but does not get the object, at this point the second thread also begins to judge the flat execution, there are many ways to solve the thread unsafe, you can add synchronized to the Getsingleton method before implementing Also consider the replication of objects. In Java, the default is not to replicate, if the implementation of the Clonable interface, and the implementation of the Clone method can be copied directly through the creation of a new object, object replication is not called the constructor, so even the private constructor can still replicate. In general, very few singleton classes will actively require replication, so do not implement the Clonable interface.
Iv. expansion of the single-case pattern
All we've seen before are singleton creation of a single object. What to do if more than one object is needed.
Fixed number of Emperors class:
1 Public classemperor{2 //define the maximum number of instance instances that can be generated3 Private Static intmaxnumofemperor=2;4 //each emperor has a name, using a ArrayList to accommodate the private properties of each object5 Private StaticArraylist<string> namelist=NewArraylist<string>();6 //define a list that accommodates all the Emperor instances7 Private StaticArraylist<emperor> emperorlist=NewArraylist<emperor>();8 //Current Emperor Serial number9 Private Static intCountnumofemperor=0;Ten //produce all the objects One Static{ A for(inti=0;i<maxnumofemperor;i++){ -Emperorlist.add (NewEmperor ("Emperor" +i+ "Emperor")); - } the } - PrivateEmperor () { - } - PrivateEmperor (String name) { + Namelist.add (name);} - Public StaticEmperor getinstance () { +Random random=NewRandom (); ACountnumofemperor=Random.nextint (maxnumofemperor); at returnEmperorlist.get (countnumofemperor); - } - Public Static voidsay () { - System.out.println (Namelist.get (Countnumofemperor));} - -}
Minister class:
1 Public classminister{2 Public Static voidMain (String[]args)3 {4 intMinisternum=5;5 for(inti=0;i<ministernum;i++){6Emperor emperor=emperor.getinstance ();7System.out.println ("the" + (i+1) + "The one who reached the worship is:");8 Emperor.say ();9 }Ten } One}
This is also called a multiple-case pattern with an upper limit.
V. Practice
In spring. The default for each bean is but it's a little bit out of the way. Spring containers can manage their lifecycles, create destruction, and so on. If non-singleton mode is used. The management of the bean after initialization is referred to the Java EE container, and the spring container no longer tracks the lifecycle of the management bean.
Design Pattern Series (i) Singleton mode