Java Singleton Mode

Source: Internet
Author: User

Concept: java Singleton mode is a common design mode. Singleton mode can be divided into three types: lazy Singleton, hungry 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 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 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, the Java reflection mechanism can be used to instantiate classes whose constructor is private, which will basically invalidate all Java Singleton implementations. 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. 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. [Java] 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 construction method without parameters // This class must be created by itself // There are two methods/* private static final TestStream ts = new TestStream (); */private static TestStream ts1 = null; // This class must automatically provide this instance object public static TestStream getTest () {if (ts1 = null) to the entire system) {ts1 = new TestStream ();} Return ts1;} public void getInfo () {System. out. println ("output message" + name) ;}[ java] 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 One instance ");} else if (s! = S1) {System. out. println ("not the same instance created");} else {System. out. println ("application error") ;}} running result: Zhang Xiaoxiang output message Zhang Xiaoxiang created the same instance. 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-type Singleton class [java] // hunger-type Singleton class. during class initialization, the public class Singleton1 {// private default constructor private Singleton1 () has been self-instantiated () {}// private static final Singleton1 single = new Singleton1 (); // static factory method public static Singleton1 getInstance () {return single ;}} 2. lazy Singleton class [java] // <span style = "color: # ff0000;"> <strong> lazy Singleton class </strong> </span>. in the first call, instantiate public class Singleton2 {// private default constructor private Singleton2 () {}// note that no fi Nal private static Singleton2 single = null; // static factory method public <span style = "color: # ff0000; "> <strong> synchronized </strong> </span> static Singleton2 getInstance () {if (single = null) {single = new Singleton2 ();} return single ;}} 3. registration type Singleton class [java] import java. util. hashMap; import java. util. map; // registered Singleton class. // similar to the method in Spring, register the class name and obtain 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 default protection constructor protected Singleton3 () {}// the static factory method returns the only 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 ());}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.