[Java design mode] (i) How to implement Singleton (singleton) mode programming

Source: Internet
Author: User

Singleton mode is the simplest and most understandable pattern in the development model. To put it simply, it means to always keep an instance of the meaning. However, the Java class can wear a number of instances, then, how to implement it?
As the name implies, Singleton mode is just one instance. The singleton pattern ensures that there is only one instance of a class, which is called a singleton class, and the singleton pattern has 3 points:
① is a class that can have only one instance;
② It must create this instance on its own;
③ is that it must provide this instance to the entire system on its own. For example, some resource managers are often designed as singleton patterns.
In a computer system, there are many resources that need to be managed, for example, each computer can have several printers, but only one print controller, to prevent two print jobs from outputting to the printer at the same time, each computer can have several fax cards, but only one software should be responsible for managing the fax card. To avoid the occurrence of two fax jobs at the same time to the fax card.
In summary, selecting Singleton mode is to avoid inconsistent states.
First look at a classic singleton pattern 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; }  }  

Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope. (In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )
However, the above implementation does not consider thread security, so-called thread safety, that is, if your code is in a process where multiple threads are running concurrently, and these threads may run this code at the same time, if the results of each run are consistent with the results of a single-threaded run, and the values of their variables are the same as expected, is thread-safe. Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization. Obviously the above implementations do not meet the requirements of thread safety, and many singleton instances are likely to occur in concurrent environments.

In Java, the implementation of the singleton mode generally pay attention to the following points:

    • A private construction method that guarantees that the class instance cannot be created externally.
    • A private static type reference. Because static can guarantee that there is only one variable reference.
    • Provides a way to get an instance. The method name is generally getinstance ().
      The singleton pattern is usually implemented in two ways: lazy and a hungry man-type
      1, lazy type
      For lazy-type, it is generally necessary in the getinstance () method to first determine whether the instance is empty, that is, the first time the access to the IF statement, and then return to the instance, such as the following code:
privatestaticnull;publicstaticgetInstance(){    if(obj==null)         new lanhanObject();//创建新的    return obj;}

Lazy There is a drawback that he may make the thread unsafe and cannot guarantee 100% of the singleton, for example, when thread A is paused in line 4th of the above code (before the IF statement, before creating the instance), thread B enters the instance. Therefore, in order to ensure that the lazy type can do 100% of the Singleton, but also to the getinstance () method plus the Synchronized keyword to ensure that thread synchronization, such as the following code:

publicstaticsynchronizedgetInstance(){//获取实例方法,保证同步    ifnull){        new lanhanObject();        }    return obj;}

Synchronized keywords can also be used in the method body, with synchronous code block form to ensure thread synchronization, not necessarily with the synchronization method.

2, a hungry man type
For a hungry man, the need to do is to write the new statement where the reference variable is defined, and then getinstance () to return directly, for example, the following code:

privatestaticnew ehanObject();  //静态的类型引用publicstaticgetInstance(){         //获取实例方法    return obj;}

There is no thread-safe problem with a hungry man, but he can cause wasted resources. Because, when the class is loaded, the instance is created with the initialization of the static variable, but sometimes it is not used, then its creation is wasted, and if the instance is larger, it will affect the performance of the program.
In short, the lazy and a hungry man style does not have the absolute merits and demerits, mainly according to the specific circumstances to decide.

Package Com.leetch.java//A Hungry man single-case advantages: simple to implement; disadvantages: When not needed, white creates objects, causing waste of resourcesClass Connectionpoola {Private StaticConnectionpoola Cpoola =NewConnectionpoola ();//Create an instance    Private  Connectionpoola() {}//Private construction method     Public StaticConnectionpoolaGetconnectionpoola() {returnCpoola; }}//Lazy single-case advantages: Create when objects are needed; disadvantage: thread insecureClass connectionpoolb{Private StaticConnectionpoolb Cpoolb;Private Connectionpoolb(){} Public StaticSynchronized ConnectionpoolbGetconneconnectionpoolb(){if(cpoolb==NULL) {Cpoolb =NewConnectionpoolb (); }returnCpoolb; }} Public classsinglobjectparttern{ Public Static void Main(String args[]) {Connectionpoola CP = Connectionpoola.getconnectionpoola ();//Create 1Connectionpoolb CP2 = Connectionpoolb.getconneconnectionpoolb ();//Create 2System. out. println (cp = = CP2); }}

Because in singleton mode, the result is always the same object, so the above code runs as follows:

true

[Java design mode] (i) How to implement Singleton (singleton) mode programming

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.