The understanding of JAVA Single example mode __java

Source: Internet
Author: User

I am learning design mode, the following is the simplest single example, the so-called single example is a single instance, is that a class can only generate one object. A single example pattern can be divided into three steps. The code is as follows:

public class Singleton
{
	private Singleton ()
	{
	
	}
	
	private static Singleton singleton=new Singleton ();
	
	Static Singleton Getsingleton (Singleton instance)
	{return
		instance;
	}	
}
The first function is a refactoring of the Singleton class construction method, which is declared private in order not to allow other classes to go directly to the new one singleton (), and the refactoring of the method is independent of the return value. Since an external class cannot generate a singleton class object, the Singleton object can only be declared inside itself, and then a reference to that type object is returned through a function.

Having identified this idea, the next step is to generate an object that, in order not to allow the external class to be referenced, is also declared private permission.

In the third step, you should declare a function that returns a reference to the Singleton class object generated in the second step. In general, however, the outer class wants to invoke the Getsingleton method by invoking a reference to the Singleton class object, because we are implementing a singleton pattern, and an instance has been generated in the second step. This is not workable. All Getsingleton methods are declared static so that the outer class can invoke the method directly through the form Singleton.getsingleton (Singleton instance). Well, write here and add static in the second step, because non-static member variables cannot be referenced in the static method.

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.