"Raise a child so expensive, or give birth to a forget it" design mode of the single-instance mode Java Edition

Source: Internet
Author: User

Defined

Singleton mode, which guarantees that a class has only one instance, and provides a global access point to access it. So when you need to make sure that there is only one instance of a class, you can refer to singleton mode. Usually we can have a global variable that makes an object accessible, but it doesn't prevent you from instantiating multiple objects. The only way to do this is to let the class itself be responsible for preserving its only instance. This class guarantees that no other instance can be created, and it can provide a way to access the instance.


Method One

One is that it is easy to think of defining a private constructor by not allowing other classes to instantiate instances of their own classes. This is because if we customize a private constructor, the default constructor of the system will be invalidated. When another class uses new to instantiate its own class object, it emits a warning that the constructor for its class cannot be accessed. This resolves an issue that prevents multiple objects from being instantiated.

Second, in order to be able to produce an instance variable of its own class, we can define a global variable of its own class object, and define a getinstance function within its own class to get the global object variable. Because the private constructor can be accessed within its own class. Here's a straight look at the Java version of the code.

Final class Singleton {private static Singleton instance;private Singleton () {};p ublic static Singleton getinstance () {if (NULL = = instance) {instance = new Singleton ();} return instance;}} public class MainClass {public static void main (string[] args) {Singleton S1 = singleton.getinstance (); Singleton s2 = singleton.getinstance (), if (S1 = = s2) {System.out.println ("two instances Same");} else {System.out.println ("Two instances are not the same" );}}}


Improved

Imagine, in the above code, if there are two threads entering the getinstance function at the same time, what will the result be? Speaking of which, you may have already understood that the above code may have multithreaded security issues. So we use lock to prevent different processes from entering the code to create their own class objects at the same time. See the following code:

Import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;final class Singleton { private static Singleton instance;private Singleton () {};p ublic static Singleton getinstance () {if (null = = instance) {INS tance = new Singleton ();} return instance;}} public class MainClass {private static lock lock = new Reentrantlock ();p ublic static void Main (string[] args) {Singleton s 1 = singleton.getinstance (); Singleton s2 = singleton.getinstance (); Lock.lock (); try {if (S1 = = s2) {System.out.println ("two instances Same");} else { System.out.println ("Two instances are not the same");}} finally {Lock.unlock ();}}}

Method Two

In order to achieve the goal of the singleton mode, we can also use a concept called "static initialization" in Java. Because we all know that a static variable is just initialized once. The concept is simple, let's look at the following code:

Import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;final class Singleton { Private static final Singleton instance = new Singleton ();p rivate Singleton () {};p ublic static Singleton getinstance () {RE turn instance;}} public class MainClass {public static void main (string[] args) {Singleton S1 = singleton.getinstance (); Singleton s2 = singleton.getinstance (), if (S1 = = s2) {System.out.println ("two instances Same");} else {System.out.println ("Two instances are not the same" );}}}


The advantage of using static initialization is thread-safe and does not have to be locked to ensure it.


Method One VS method two

Method one, the class needs to be instantiated to be instantiated, and method Two is that once the class is loaded, it will be instantiated, so method two needs to occupy the system resources in advance. But method one in multithreaded security to see the code is more concise, no need for additional code.





"Raise a child so expensive, or give birth to a forget it" design mode of the single-instance mode Java Edition

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.