Design mode: single-case mode

Source: Internet
Author: User

Overview: Like the Task Manager for Windows systems, you always display a window no matter how many times you open it. How to ensure that a class has only one instance and that this instance is easy to access, defining a unified global variable ensures that objects are accessible at all times, but does not prevent multiple objects from being created. One of the best ways is to have the class itself responsible for creating and saving the only instance of it, and to ensure that no other instances are created, and that it provides a way to access that instance, which is the motivation of the singleton pattern. It's not frozen.-_-| |

Definition of a singleton pattern:

Singleton mode: Ensures that a class has only one instance and provides a global access point to access this unique instance.

Singleton pattern:ensure A class have only one instance, and provide a global point of access to it.

Singleton mode is an object-creation pattern. The singleton mode has three points: first, there is only one instance of a class, and the other is that it must create it on its own, and thirdly, it must provide this instance as an entire system.

The structure of the singleton pattern:

The singleton pattern is the simplest design pattern of the structure, which contains only one class, the Singleton class.

The implementation of the Singleton pattern:

     Public classSingletonpattern {//static Private member variable        Private StaticSingletonpattern instance =NULL; //Privatization Constructors        PrivateSingletonpattern () {}//Static Private Factory method returns a unique instance         Public StaticSingletonpattern getistance () {if(Instance = =NULL) Instance=NewSingletonpattern (); returninstance; }    }

From the code can be seen in the implementation of the singleton mode, you need to pay attention to three points:

1: Privatisation constructor private

2: Provide a self-static private member variable

3: Provide a public static factory method

A hungry man type single case (Eager Singleton):

    

One: A hungry man mode, code such as so:

     Public class Eagersingleton    {        privatestaticnew  Eagersingleton ();         Private Eagersingleton () {}              Public Static Eagersingleton getinstance ()        {            return  instance;        }    }

When the class is loaded, the static variable instance is initialized, and the private constructor of the class is called, and the Singleton class unique instance is created.

Two: Lazy mode
As with the A Hungry man pattern Singleton class, the Lazy Singleton class (lazy Singleton) constructor is also private, unlike the A Hungry man Singleton class, where the lazy singleton class is instantiated the first time it is referenced and does not instantiate itself when the lazy singleton class is loaded.

As you can see in the Lazy Singleton class, the Singleton class is not instantiated when the static variable is defined, but the Singleton class is instantiated the first time the static factory is called.

The code is as follows:

     Public classLazysingleton {Private StaticLazysingleton instance =NULL; //Create a static read-only helper object while the program is running        Private Static ReadOnly ObjectSyncRoot =New Object(); PrivateLazysingleton () {} Public StaticLazysingleton getinstance () {//first judgment, the first judge whether the existence of the case, there is no additional lock processing            if(Instance = =NULL)            {                //A locked program allows only one thread to access at a time                Lock(syncRoot) {//Second Judgment                    if(Instance = =NULL) {instance=NewLazysingleton ();//Create an instance of a singleton                    }                }            }            returninstance; }    }

From the code can see lock, why lock it? is because the lazy singleton has a serious problem: if you implement a lazy singleton in a high-concurrency, multi-threaded environment, there may be multiple threads that need to use singleton objects at some point, i.e. multiple threads calling the GetInstance () method at the same time may cause multiple instance objects, This will violate the design intent of the singleton pattern. To prevent multiple singleton objects from being generated, you need to use the lock keyword, which means that a locked code fragment becomes a critical section, ensuring that a thread is in the critical section of the code. Another thread cannot enter the critical section. If another thread view enters the locked code, it waits until the object is released.

A hungry man comparison of single and lazy-type single cases:

The advantage of the A hungry man singleton is that it instantiates itself when the class is loaded, which ensures that the instance is unique without having to consider the problem of simultaneous access by multiple threads. From the invocation speed, since the singleton object was created at the beginning, it is better than the lazy one. However, regardless of whether the system needs to use the Singleton object at run time, because the object needs to be created when the class is loaded, from the point of view of resource utilization efficiency, a hungry man-type single-case lazy type single case, and in order to create an orderly system load a hungry man singleton object, load time will be longer.

Lazy single-case in the first use of the creation, do not have to occupy the system resources, the implementation of lazy loading, but must handle the problem of multiple threads simultaneous access, especially when the Singleton class as a resource controller, when instantiated will inevitably involve the initialization of resources, and the initialization of resources need to consume a lot of events, This means that there is a greater chance that multiple threads will be referenced at the same time for the first time, and control through mechanisms such as double-check locking, which can result in system performance being affected.

Advantages and disadvantages of the singleton model:

Pros (1): Provides controlled access to a unique instance.

(2): There is only one object in the system memory, so you can save the resources of the system, for some objects that need to be created and destroyed frequently, using singleton mode is undoubtedly improving the performance of the system.

(3): Singleton mode allows variable number of instances. Based on the singleton pattern can be extended, using a method similar to the control of a single object to obtain a specified number of instance objects, not only save the system resources, but also to solve the single-instance object sharing too much lossy performance problem (the class that provides the specified number of instances object can become a multi-Class)

Disadvantage (1): Because the singleton pattern does not have an abstraction layer, it is difficult to expand.

(2): a single case of excessive responsibility, to a certain extent, contrary to a single duty. Because the Singleton class provides both a business approach and a method for creating objects (factory methods), the creation of objects is coupled with the functionality of the object itself.

(3): garbage collection mechanism, if the instantiated shared object for a long time is not exploited, the system will consider it to be garbage, will automatically destroy and reclaim resources. The next time it is exploited, it will be re-instantiated, which will result in the sharing of singleton object state loss.

Usage environment for Singleton mode:

As a kind of design pattern with clear target, simple structure and easy to understand, the singleton pattern is used very frequently in software development and widely used in many application software and frameworks.

You might consider using singleton mode in the following situations:

1: The system requires only one instance object, such as Windows Explorer, or because the resource consumption is too large to allow only one object to be created

2: Customer calls a single instance of a class allows only one public access point, except for that public access point, which cannot be accessed by other means.

Hungry to read the 23 design model, my little brother, just touch the design mode, Khan Ah-_-| |, object-oriented, object-oriented, object-oriented. The important thing to say three times, the next bath to eat, come back to continue.

Design mode: single-case 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.