Single-Case mode

Source: Internet
Author: User

Role

Ensure that a class has only one instance and provides an access point to the outside.

Application Scenarios

Task Manager in Windows is a typical singleton pattern.

Classes that read a configuration file generally have only new objects, and it is not necessary to re-new an object every time the configuration file is read.

Website counters also use a singleton mode, otherwise it is difficult to synchronize

Application log files are typically maintained with only one object

The design of the database link pool also uses a singleton pattern.

The file system is also a singleton mode, and an operating system can have only one file system.

In spring, each bean is singleton by default, so that the spring container is easy to manage.

Each servlet in the Javaweb is a singleton

Advantages

Because only one instance is generated, system overhead is reduced. You can set the global access point on the system to optimize shared resource access.

Classification

Main

    • a hungry man type (Thread-safe, high-efficiency, but not time-delayed loading)

    • Lazy Type (thread safe, call inefficient, can delay load)

Other

    • Double detection lock type (problems sometimes occur due to JVM reasons)
    • static internal class type (Thread safety, high call efficiency, can be delayed loading)
    • Enumeration Single Example (thread safe, call inefficient, cannot delay loading)
Example
    • A Hungry man type

As soon as the object is created, immediately loaded, the problem is that the object may not be used, wasting memory resources

 PackageCom.dy.xidian; Public classSingleDemo1 {//class initialization is the immediate loading of an object//The JVM will only load the class once, and an instance will be created when the class is loaded    Private StaticSingleDemo1 instance =NewSingleDemo1 (); //the constructor is privatized and cannot be a new object    PrivateSingleDemo1 () {}//provides an external access interface because only one instance exists, so thread-safe     Public StaticSingleDemo1 getinstance () {returninstance;}}
    • Lazy type

Time to create an object and delay load. Because the synchronization mechanism is added, the call efficiency is not high

 PackageCom.dy.xidian; Public classSingleDemo2 {Private StaticSingleDemo2 instance; PrivateSingleDemo2 () {}//an object is instantiated only when it is called//a race condition exists and should be synchronized     Public Static synchronizedSingleDemo2 getinstance () {if(Instance = =NULL) Instance=NewSingleDemo2 (); returninstance; }}

    • Dual detection Lock implementation

The synchronization block is placed inside the method so that it can not only delay loading, but also improve the efficiency of the call. However, due to compiler optimizations and the underlying internal model of the JVM, problems occasionally occur, and it is not recommended to use

 PackageCom.dy.xidian; Public classSingleDemo3 {Private StaticSingleDemo3 instance; PrivateSingleDemo3 () {} Public StaticSingleDemo3 getinstance () {if(Instance = =NULL) {SingleDemo3 sc; synchronized(SingleDemo3.class) {SC=instance; if(sc = =NULL){                    synchronized(SingleDemo3.class) {                        if(sc = =NULL) SC=NewSingleDemo3 (); }} instance=SC; }        }        returninstance; }}

    • Static inner class mode

The JVM initializes the class SingleDemo4 and does not go inside the initial session, so it avoids loading the object as soon as it is a hungry man-like.

The inner class is only loaded if getinstance () is actually called. While loading a class is thread-safe, final guarantees that only such an instance exists in memory, with the advantage of efficient invocation and lazy loading.

 PackageCom.dy.xidian; Public classSingleDome4 {PrivateSingleDome4 () {}Private Static classsingleclassinstance{Private Static FinalSingleDome4 instance =NewSingleDome4 (); }         Public StaticSingleDome4 getinstance () {returnsingleclassinstance.instance; }}
    • Enumeration mode

The enumeration class is inherently singleton, but it cannot be loaded lazily

 Package Com.dy.xidian;  Public enum SingleDome4 {    INSTANCE;     New String ();     // Processing Methods     Public Static void Main (string[] args) {        System.out.println (singledome4.instance);         = "ff";        System.out.println (SINGLEDOME4.INSTANCE.A);    }}

Single-Case mode

Related Article

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.