Android training Java training is coming to be discussed with you!
Java Singleton mode is a common design mode. Singleton mode is divided into three types: lazy Singleton, ELE. Me Singleton, and registered Singleton.
The Singleton mode has the following features:
1. A singleton class can only have one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system. In computer systems, driver objects of thread pools, caches, log objects, dialogs, printers, and graphics cards are often designed as Singleton. These applications have more or less resource manager functions. Each computer can have several printers, but only one printer spooler can be used to prevent two print jobs from being output to the printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being simultaneously called by both requests. In short, the singleton mode is selected to avoid inconsistency and avoid multiple leaders.
First, let's look at a classic Singleton implementation.
Public ClassSingleton {
Private StaticSingletonUniqueinstance=Null;
PrivateSingleton (){
// Exists only to defeat instantiation.
}
Public StaticSingleton getinstance (){
If(Uniqueinstance=Null){
Uniqueinstance=NewSingleton ();
}
Return Uniqueinstance;
}
// Other methods...
}
Singleton limits the constructor to private to avoid class instantiation outside. Within the same Virtual Machine range, Singleton's unique instance can only be accessed through the getinstance () method. (In fact,PassThe Java reflection mechanism can instantiate classes whose constructor method is private, which basically makes all JavaThe single instance is invalid.We will not discuss this issue here, so we may think that the reflection mechanism does not exist .)
However, the preceding implementation does not consider thread security issues. Thread security means that if multiple threads run simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe. In other words, the interface provided by a class or program is an atomic operation for a thread or the switching between multiple threads does not lead to ambiguity in the execution result of this interface, that is to say, we do not need to consider synchronization issues. Obviously, the preceding implementation does not meet the thread security requirements. Multiple Singleton instances may appear in the concurrent environment.
1 public class teststream {
2 Private string name;
3 Public String getname (){
4 return name;
5}
6 Public void setname (string name ){
7 This. Name = Name;
8}
9 // This class can only have one instance
10 private teststream () {}// private construction method without Parameters
11 // This class must be created by yourself
12 // There are two methods
13/* Private Static final teststream Ts = new teststream ();*/
14 Private Static teststream ts1 = NULL;
15 // This class must automatically provide this instance object to the entire system
16 public static teststream gettest (){
17 if (ts1 = NULL ){
18 ts1 = new teststream ();
19}
20 return ts1;
21}
22 public void getinfo (){
23 system. Out. println ("Output Message" + name );
24}
25}
1 public class testmain {
2 public static void main (string [] ARGs ){
3 teststream S = teststream. gettest ();
4 S. setname ("Zhang Xiaoxiang ");
5 system. Out. println (S. getname ());
6 teststream S1 = teststream. gettest ();
7 s1.setname ("Zhang Xiaoxiang ");
8 system. Out. println (s1.getname ());
9 s. getinfo ();
10 s1.getinfo ();
11 if (S = S1 ){
12 system. Out. println ("the same instance is created ");
13} else if (s! = S1 ){
14 system. Out. println ("not the same instance created ");
15} else {
16 system. Out. println ("application error ");
17}
18}
19}
Running result:
Zhang Xiaoxiang
Zhang Xiaoxiang
Output Message Zhang Xiaoxiang
Output Message Zhang Xiaoxiang
The same instance is created.
Conclusion: The result shows that the singleton mode provides a unique object access point for an object-oriented application. No matter what features it implements, the entire application shares an instance object.
1. Hunger examples
1 // empty Chinese Singleton class. It has been self-instantiated during class initialization.
2 public class singleton1 {
3 // Private default constructor
4 private singleton1 (){}
5 // self-instantiated
6 Private Static final singleton1 single = new singleton1 ();
7 // static factory Method
8 public static singleton1 getinstance (){
9 return single;
10}
11}
2. Lazy Singleton type
1 // lazy Singleton class. instantiated during the first call
2 public class singleton2 {
3 // Private default constructor
4 private singleton2 (){}
5 // note that there is no final
6 Private Static singleton2 single = NULL;
7 // static factory Method
8 Public synchronized static singleton2 getinstance (){
9 If (single = NULL ){
10 single = new singleton2 ();
11}
12 Return single;
13}
14}
3. Registration type Singleton type
1 import java. util. hashmap;
2 Import java. util. Map;
3 // registration type Singleton type.
4 // similar to the method in spring, register the class name and obtain it directly from it next time.
5 public class singleton3 {
6 Private Static Map <string, singleton3> map = new hashmap <string, singleton3> ();
7 static {
8 singleton3 single = new singleton3 ();
9 map. Put (single. getclass (). getname (), single );
10}
11 // protect the default constructor
12 protected singleton3 (){}
13 // The static factory method to return such a unique instance
14 public static singleton3 getinstance (string name ){
15 if (name = NULL ){
16 name = singleton3.class. getname ();
17 system. Out. println ("name = NULL" + "---> name =" + name );
18}
19 if (Map. Get (name) = NULL ){
20 try {
21 map. Put (name, (singleton3) class. forname (name). newinstance ());
22} catch (instantiationexception e ){
23 E. printstacktrace ();
24} catch (illegalaccessexception e ){
25 E. printstacktrace ();
26} catch (classnotfoundexception e ){
27 E. printstacktrace ();
28}
29}
30 return map. Get (name );
31}
32 // a schematic commercial Method
33 Public String about (){
34 return "Hello, I am regsingleton .";
35}
36 public static void main (string [] ARGs ){
37 singleton3 single3 = singleton3.getinstance (null );
38 system. Out. println (single3.about ());
39}
40}