Singleton pattern concept:
Singleton pattern in Java is a common design pattern. Singleton pattern is divided into three types: lazy singleton, hungry singleton, and registered singleton.
The singleton mode has the following characteristics:
1. There can only be one instance in a singleton class.
2. The singleton class must create its own unique instance.
3. The singleton class must provide this instance to all other objects.
Singleton pattern ensures that a class has only one instance, and instantiates it itself and provides this instance to the entire system. In computer systems, driver objects for thread pools, caches, log objects, dialog boxes, printers, and graphics cards are often designed as singletons. These applications have more or less the functionality of a resource manager. Each computer can have several printers, but only one Printer Spooler can be available to avoid two print jobs being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to avoid one communication port being called simultaneously by two requests. In short, choosing a singleton model is to avoid inconsistent states and avoid political bullishness.
First, let’s look at a classic singleton implementation.
public class Singleton { private static Singleton uniqueInstance = null; private Singleton() { // Exists only to defeat instantiation. } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // Other methods...}Singleton avoids the class being instantiated externally by limiting the constructor to private. In the same virtual machine scope, the only instance of Singleton can only be accessed through the getInstance() method. (In fact, through the Java reflection mechanism, you can instantiate a class with a private construct, which will basically invalidate all Java singleton implementations. This issue will not be discussed here, and I will think that the reflection mechanism does not exist.)
However, the above implementation does not consider thread safety issues. Thread safety means: if your code is in a process where multiple threads are running at the same time, and these threads may run this code at the same time. If the result of each run is the same as the result of a single thread run, and the values of other variables are 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 will not cause ambiguity to the execution result of the interface, that is, we do not need to consider the synchronization issue. Obviously, the above implementation does not meet the thread safety requirements, and multiple Singleton instances are likely to appear in a concurrent environment.
public class TestStream { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //This class can only have one instance private TestStream(){} //Private non-argument constructor//This class must be created by itself//There are 2 ways/*private static final TestStream ts=new TestStream();*/ private static TestStream ts1=null; //This class must automatically provide this instance object to the entire system public static TestStream getTest(){ if(ts1==null){ ts1=new TestStream(); } return ts1; } public void getInfo(){ System.out.println("output message "+name); } } public class TestMain { public static void main(String [] args){ TestStream s=TestStream.getTest(); s.setName("Zhang Xiaoxiang"); System.out.println(s.getName()); TestStream s1=TestStream.getTest(); s1.setName("Zhang Xiaoxiang"); System.out.println(s1.getName()); s.getInfo(); s1.getInfo(); if(s==s1){ System.out.println("The same instance was created"); }else if(s!=s1){ System.out.println("created not the same instance"); }else{ System.out.println("application error"); } } } }Running results:
Zhang Xiaoxiang Zhang Xiaoxiang
output message Zhang Xiaoxiang
output message Zhang Xiaoxiang created the same instance
Conclusion: From the results, we can see that the singleton pattern provides an object-oriented application with the unique access point for an object. No matter what function it implements, the entire application will share an instance object.
1. Hungry singleton
//Hungry singleton class. When class initialization, public class Singleton1 has been instantiated itself { //Private default constructor private Singleton1() {} //Add private static final Singleton1 single = new Singleton1(); //Static factory method public static Singleton1 getInstance() { return single; } } 2. Lazy singleton class
//Laggy singleton class. Instantiate public class Singleton2 when called first time public class Singleton2 { //Private default constructor private Singleton2() {} //Note that there is no final private static Singleton2 single=null; //Static factory method public synchronized static Singleton2 getInstance() { if (single == null) { single = new Singleton2(); } return single; } } 3. Registered singleton class
import java.util.HashMap; import java.util.Map; //Registered singleton class. // Similar to the method in Spring, register the class name and get it directly from it next time. public class Singleton3 { private static Map<String,Singleton3> map = new HashMap<String,Singleton3>(); static{ Singleton3 single = new Singleton3(); map.put(single.getClass().getName(), single); } //The protected default constructor protected Singleton3(){} // Static factory method, return this class's unique instance public static Singleton3 getInstance(String name) { if(name == null) { name = Singleton3.class.getName(); System.out.println("name == null"+"--->name="+name); } if(map.get(name) == null) { try { map.put(name, (Singleton3) Class.forName(name).newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return map.get(name); } //A schematic commercial method public String about() { return "Hello, I am RegSingleton."; } public static void main(String[] args) { Singleton3 single3 = Singleton3.getInstance(null); System.out.println(single3.about()); } } The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.