Basic Concepts
Singleton is a creation model that ensures that only one instance is generated and provides a global access point to access it. for some classes, it is very important to ensure only one instance. For example, sometimes database connections or socket connections are restricted, and only one connection can exist at a time. for another example, the set in the set cannot contain duplicate elements. The objects added to the set must be unique. If the repeated values are added to the set, only one instance is accepted. JDK uses the singleton mode to implement the set feature. You can refer to Java. util. the original Code . In fact, Singleton is the simplest but also one of the most widely used models, which can be seen everywhere in JDK.
Simple Analysis
To implement the singleton mode, we need a static variable to remember whether an instance has been generated without creating an object. static variables or static methods can be called without generating a specific instance. Such variables or methods will not change because of class instantiation. in the structure shown in figure 1, we can see that uniqueinstance is an independent static variable. It can remember whether the object has been instantiated and judge this variable in the static method instance, A new object is generated if it has not been instantiated. If it has already been instantiated, no new object is generated and the previously generated instance is still returned.
Figure 1: Singleton mode structure
Implementation
There are usually three ways to implement the singleton mode.
1. Use the static method to implement singleton. This method uses the static method to monitor instance creation. To prevent the creation of more than one instance, we 'd better declare the constructor as private.
This prevents customers from Program The compiler creates an instance in any way except the methods we provide. If the constructor is not declared as private, the compiler automatically synchronizes a default friendly constructor. this implementation method is the most common, that is, the standard implementation of the structure in Figure 1.
public class Singleton {
Private Static Singleton s;
private Singleton (){};
/**
* class method to access the singleton instance of the class.
*/
Public static Singleton getinstance () {
If (S = NULL)
S = new Singleton ();
return s;
}< BR >}< br> // test class
class singletontest {
Public static void main (string [] ARGs) {
Singleton S1 = Singleton. getinstance ();
Singleton S2 = Singleton. getinstance ();
If (S1 = S2)
system. out. println ("S1 is the same instance with S2");
else
system. out. println ("S1 is not the same instance with S2");
}< BR >} |
The running result of singletontest is:
S1 is the same instance with S2
This proves that we have created only one instance.
2. Use static variables as the flag to implement Singleton embedding a static variable in the class as the flag. Check every time you enter the constructor.
The problem is that the constructor does not return a type. If you are sure that an instance is successfully created. one method is to call a function to check whether the creation is successful, and then simply return a value from the static variable, but this is not elegant and prone to errors. it is better to create a class that can throw an exception when more than one instance is created. This class only calls the parent class method, and the advantage is that it uses its own exception type, the error message is clearer:
Class singletonexception extends runtimeexception {
Public singletonexception (string s ){
Super (s );
}
}
Class Singleton {
Static Boolean instance_flag = false; // true if 1 instance
Public Singleton (){
If (instance_flag)
Throw new singletonexception ("only one instance allowed ");
Else
Instance_flag = true; // set flag for 1 instance
}
}
// Test class
Public class singletontest {
Static public void main (string argv []) {
Singleton S1, S2;
// Create one incetance -- This shoshould always work
System. Out. println ("creating one instance ");
Try {
S1 = new Singleton ();
} Catch (singletonexception e ){
System. Out. println (E. getmessage ());
}
// Try to create another Spooler -- shocould fail
System. Out. println ("creating two instance ");
Try {
S2 = new Singleton ();
} Catch (singletonexception e ){
System. Out. println (E. getmessage ());
}
}
} |
The running result of singletontest is:
Creating one instance
Creating two instance
Only one instance allowed
We can see that the first instance was successfully created, and the second instance was created, throwing a custom exception.
III. use the register mechanism to create singleton. First, use hashtable and enumeration in the set to implement additem (Object key, object value), getitem (Object Key), and removeitem (objectkey) to implement a manager and associate the key and value one by one. Before creating an instance, the client programmer registers the instance using the additem method and obtains the instance using the getitem method. the key in hashtable is unique, so that the created instance is unique. The specific implementation is not detailed in length. In the article on prototype model application, I will provide a code to implement the register. the advantage of using the register mechanism to create the singleton mode is that it is easy to manage and can control multiple Singleton instances of different types at the same time.
Summary
- The Singleton mode can be easily expanded to generate a specified number of instances.
- In the design patterns Java companion book, I mentioned the use of static classes to implement the singleton mode, and pointed out that Java. lang. math is an example. I do not agree here, because math is not a real object. We just call the static method encapsulated by the math class directly, there is no process for creating an instance at all. Where can we start to generate only one instance? I have posted a post on the javaranch Forum. all replies are also negative about this point.
- In a multi-threaded program, Singleton may become unreliable and multiple instances may appear. The solution is simple. Add a synchronization modifier: public static synchronized Singleton getinstance (). this ensures thread security.
- In the end, you may see some other methods to implement the singleton mode, because the mode is flexible in the specific application, not static, and there is no fixed approach, but most of them are the variants of the above methods.
|