Gof design mode 1: Single case design mode

Source: Internet
Author: User

1. The core role of the single case design mode:

Guarantees that there is only one instance of a class and provides a global access point to access the instance

2. Common Application Scenarios:
    • Task Manager for Window
    • Reading a configuration file in a project is generally a singleton mode
    • The design of the database connection pool is also in singleton mode because the database connection is a database resource
    • The operating system of the file management system, is also a singleton mode, an operating system can have only one file system
    • Application is also a singleton application (Servlet programming or Android application Class)
    • In spring, each bean is a singleton by default, something that the spring container can manage
    • In servlet programming, each servlet is a singleton
    • In the spring MVC and STRUTS1 framework, the Controller object is also a singleton
3. Advantages of Singleton mode
    • Because the singleton mode only produces one object, reduces the system overhead, when an object's generation requires more resources, such as reading the configuration file, generating other dependent objects, you can directly produce a singleton object when the application starts, and then permanent memory in the way to solve.
    • Singleton mode optimizes access to shared resources by setting up global access points on the system. For example, you can design a singleton class that is responsible for mapping all the data tables.
4. Common 5 The implementation of the singleton mode:

Main

A hungry man: thread-safe, high-efficiency calls. But can't delay loading

Lazy: Thread-safe, call efficiency is not high. However, you can delay loading

Other:

Double-Lock: Because of the JVM's underlying internal model, occasional problems may occur, and it is not recommended to use

Static internal class: Thread-safe, high-efficiency calls, and can delay loading

Enumeration Singleton: Thread safety, high call efficiency, non-lazy loading

Example code for the A Hungry man type:

 Public class Singleton01 {    /// class is initialized, the object is loaded immediately (without the advantage of inertia loading). When the class is loaded, it is thread-safe    privatestaticnew  Singleton01    (); Private Singleton01 () {}     // method has high    efficiency without synchronous calls  Public Static Singleton01 getinstance () {        return  instance;    }}

In the code of the A Hungry man singleton pattern, the static variable is initialized when the class is loaded, and there is no problem involving multiple thread objects accessing the object. The virtual opportunity guarantees that the class will be loaded only once, and there is no problem with concurrent access, so you can omit the Synchronized keyword

Problem: If you simply load this class instead of calling getinstance, or even never calling it, you will waste resources.

Lazy example Code

1  PackageCom.chunjiangchao.pattern.singleton;2 /**3 * Test Lazy single-case mode4  */5  Public classSINGLETON02 {6     //when the class is initialized, the object is not initialized (deferred loading, which is created when it is actually used). 7     Private StaticSingleton02 instance =NULL;8     PrivateSingleton02 () {}9     ////method synchronization, the call efficiency is low! Ten      Public Static synchronizedSingleton02 getinstance () { One         if(Instance = =NULL) AInstance =NewSingleton02 (); -         returninstance; -     } the}

Important: Lazy loading is the only option to load when it is actually used.

Problem:

Resource utilization is high, but each call to the getinstance () method is synchronized, and the concurrency is less efficient.

Double check Lock implementation

1  PackageCom.chunjiangchao.pattern.singleton;2 /**3 * Test DCL (double check lock) Single case mode4  * 5  */6  Public classSingleton03 {7     //when the class is initialized, the object is not initialized (deferred loading, which is created when it is actually used). 8     Private volatile StaticSingleton03 instance =NULL;9     PrivateSingleton03 () {}Ten     ////code block synchronization, the call efficiency is faster than the synchronization method, due to the JVM's cause in the case of high concurrency problems One      Public StaticSingleton03 getinstance () { A         if(Instance = =NULL){ -             synchronized(Singleton03.class) { -                 if(Instance = =NULL) theInstance =NewSingleton03 (); -             } -         } -         returninstance; +     } -}

Improves the efficiency of execution without having to synchronize every time an object is acquired, only the first time it is created synchronously.

Problem:

Due to compiler optimizations and the underlying internal model of the JVM, there are occasional problems that are not recommended. But we can add the volatile keyword in front of the instance, so there's no problem.

Static inner class implementation mode: (Lazy loading mode)

1  PackageCom.chunjiangchao.pattern.singleton;2 /**3 * Static internal class Singleton mode4 * This way: thread-safe, high-efficiency calls, and the implementation of delay loading! 5  */6  Public classSingleton04 {7     PrivateSingleton04 () {}8      Public StaticSingleton04 getinstance () {9         returninner.instance;Ten     } One     Private Static classinner{ A         Private StaticFinal Singleton04 instance =NewSingleton04 (); -     } -}

The outer class does not have a static property, so it does not come up with the object as a hungry man.

Static inner classes are loaded only if you really call getinstance. It is thread-safe to load a class. Instance is a static final type that ensures that only such an instance exists in memory and is assigned only once, ensuring thread safety.

The benefits of merging concurrent efficient calls and lazy loading.

In other words, the static interior has the advantage of a hungry man and delayed loading.

Enumeration Implementation Singleton:

1  PackageCom.chunjiangchao.pattern.singleton;2 /**3 * Enum Implementation singleton mode (no delay loading)4  */5  Public enumSingleton05 {6Instance//This enumeration element is itself a singleton! 7      Public voidoperation () {8         //Add the action you want9     }Ten}

Pros: Simple to implement; The enumeration itself is a singleton. The JVM provides a fundamental guarantee. Vulnerabilities to avoid reflection and serialization

Cons: No delay loading

5. How to choose these five types of singleton mode?

Singleton objects consume less resources and do not require lazy loading:

Enumeration better than a hungry man type

Singleton objects occupy large resources and require lazy loading

Static inner class better than lazy type

6. Questions

Reflection can break the implementation of the above (without enumeration) (preventing the practice of manually throwing exceptions in the constructor method)

Deserialization can be implemented by cracking (without enumeration)

You can prevent the acquisition of different objects by defining readresolve. When deserializing, if the class that contains the object defines the Readresolve () method (a callback method), return the object that you created.

Gof design mode 1: Single case design mode

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.