A single-instance pattern of Java design patterns

Source: Internet
Author: User

These two days, I learned one of the simplest patterns in Java design Patterns--singleton mode.

It is said that in the Java design pattern, the total can be divided into 23 kinds: Singleton mode, abstract Factory mode, builder mode, prototype mode and so on.


Design patterns: In fact, is a set of repeated use, most people know, through the classification of the purpose of writing, code design experience Summary. Design patterns are used in order to reuse code and make it easier for others to understand. and ensure the reliability of the code.


Single-Case mode:

In the actual application, some objects we need only one is enough, such as: Configuration file, tool class, thread pool, cache, log object, database connection object, etc.


If multiple instances are created, there can be many problems, such as excessive resources, inconsistent results, and so on, which can be solved by using a singleton pattern to ensure that an instance of the entire application has only one.


Common Singleton Patterns:

A hungry man mode, lazy mode


How to use:

First, a hungry man mode

Package com.demo;/** * Singleton mode SingleTon * Application: In the actual application, some objects only need one is enough, such as configuration file, database connection object, etc. * role: To ensure that an instance of the entire application has and only one * type: A hungry man mode, lazy mode * @author Likang * Current: A hungry man mode */public class SingleTon {/** * First step: Privatize the construction method, do not allow external direct creation of objects, can only class themselves to create */private SingleTon () {}/** * Two steps: To create a unique instance of the class, within the class by the class to create themselves, that time, the problem comes, if only this, external * can not directly invoke the class instance, so also must add the static keyword to decorate, the instance becomes the member object of the class, then the external * You can get this instance directly through the class. Member variable */private static SingleTon instsnce = new SingleTon ();/** * Step three: According to the object-oriented thought, in order to control the external cannot directly access the instance of the class, The member objects of the class are also required to be encapsulated in a certain way, which is decorated by the private keyword and can only be accessed by the class itself. External cannot be accessed directly, * as a result, the external cannot pass the class. member object to get the instance, so inside the class you must also provide a public * method (which is decorated by the publicly) for external invocation to get the instance, and the method also needs to be decorated with the static keyword. becomes a member of the class (because it cannot be created with the New keyword). ) * @return */public static SingleTon getinstance () {/** * a hungry man mode: Because the instance declaration is for the static adornment, belongs to the class, and the static member variable * is loaded with the load of the class. Regardless of whether the user has called this class, there is no use of this class, as long as the class once loaded, * then the static member variable will be loaded, as if not full, the image is called "A Hungry Man mode" */return instsnce;}

Second, lazy mode

Package com.demo;/** * Lazy mode * @author Likang * */public class SingleTon2 {/** * First step: Privatize the construction method, do not allow external direct creation of the instance */private singlet On2 () {}/** * Step two: Just declare a unique instance of the class, do not create, use private static adornment */private static SingleTon2 instance;/** * Step three: Provide a way to get an instance for external invocation, Use the public static modifier * @return */public static SingleTon2 getinstance () {/** * lazy mode: When a class is loaded, it simply declares an instance of a class and does not create it, * and when the user really uses it, the real tune Use, then to create an instance of the class, if it is the first time * is called, instance is obviously empty, then create a, and then call again, * can not be created, directly used. */if (Instance = = null) {instance = new SingleTon2 ();} return instance;}}


Test results:

Package Com.demo;public class Test {public static void main (string[] args) {/*singleton S1 = singleton.instsnce; SingleTon s2 = Singleton.instsnce;*/singleton S1 = singleton.getinstance (); SingleTon s2 = singleton.getinstance ();//Determine if the two instances of S1 and S2 are the same instance if (S1 = = s2) {System.out.println ("S1 and S2 are the same instance");} Else{system.out.println ("S1 and S2 are not the same instance");} SingleTon2 s3 = Singleton2.getinstance (); SingleTon2 S4 = Singleton2.getinstance ();//Determine if the two instances of S3 and S4 are the same instance if (s3 = = S4) {System.out.println ("S3 and S4 are the same instance");} Else{system.out.println ("S3 and S4 are not the same instance");}}}






About the difference between the A hungry man mode and the lazy model:

1, a hungry man mode is characterized by the slow loading of classes, but the runtime to get objects faster, Thread Safety
2. Lazy mode is characterized by the faster loading of classes, but the slower the runtime gets objects (first call), Thread not secure

Because the A hungry man mode is created after the class has been loaded, it will take up some system resources and will be slower, but the runtime can be used directly, and it will be faster.

While the lazy mode, when the class is loaded, just declare the instance, and not to create, but when the user actually calls to create the instance, but the first call needs to be created, again can be used directly.


The problem of thread safety is not very clear now, and then slowly to learn. Well, may be a bit verbose, because my brain has always been not so good, often others can understand the things and I often need to spend more time to understand slowly, this way is only to facilitate themselves to better understand the single case of this design pattern. Well, make progress slowly!

A single-instance pattern of Java design patterns

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.