Single-Case mode

Source: Internet
Author: User

Mode motive

For some classes in the system, only one instance is important, for example, there can be multiple print tasks in a system, but only one task is working; a system can have only one window manager or file system; A system can have only one timing tool or ID (ordinal) generator.

How do you ensure that there is only one instance of a class and that this instance is easy to access? Defining a global variable ensures that an object can be accessed at any time, but it does not prevent us from instantiating multiple objects.

A better solution is to have the class itself responsible for preserving its only instance. This class guarantees that no other instance is created, and it can provide a way to access the instance. This is the pattern motive of the singleton pattern.

Pattern Definition

Singleton mode (Singleton pattern): A singleton pattern ensures that a class has only one instance, and instantiates it itself and provides it to the entire system, a class called a singleton class that provides a method for global access.

The main points of the singleton pattern are three:

One is that a class can have only one instance;

The second is that it must create this instance on its own;

Thirdly, it must provide this instance to the whole system on its own.

Singleton mode is an object-creation pattern. The singleton mode is also a list-piece mode or a single-state mode.

Pattern Structure

The singleton pattern contains the following roles:

    • Singleton: Single case
Timing Diagram Program Analysis One: Lazy mode
//Lazy Type Singleton class. Instantiate yourself at the first call Public classSingleton {PrivateSingleton () {}Private StaticSingleton single=NULL; //Static Factory Method     Public StaticSingleton getinstance () {if(single =NULL) { single=NewSingleton (); }          returnSingle ; }}

Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope.

Increase thread safety issues

1, on the GetInstance method plus synchronization

//Lazy Type Singleton class. Instantiate yourself at the first call Public classSingleton {PrivateSingleton () {}Private StaticSingleton single=NULL; //Static Factory Method     Public Static synchronizedSingleton getinstance () {if(single =NULL) { single=NewSingleton (); }          returnSingle ; }}

2. Double check Lock

 Public Static Singleton getinstance () {        ifnull) {              synchronized (Singleton.  Class                 ){ifnull) {                    new  Singleton ();                }              }          }           return Singleton;     }

3. Static internal class

 Public classSingleton {Private Static classLazyholder {Private Static FinalSingleton INSTANCE =NewSingleton (); }      PrivateSingleton () {} Public Static FinalSingleton getinstance () {returnlazyholder.instance; }  }  

Pattern Analysis

The purpose of the singleton pattern is to ensure that a class has only one instance and provides a global access point to access it. The singleton pattern contains only one character, which is a singleton class--singleton. The Singleton class has a private constructor that ensures that the user cannot instantiate it directly with the new keyword. In addition, the schema contains a static private member variable and a static public factory method that verifies the existence of the instance and instantiates itself, and then stores it in a static member variable to ensure that only one instance is created.

In the implementation of the Singleton mode, the following three points need to be noted:

    • The constructor of a singleton class is private;
    • Provides a static private member variable of its own;
    • Provides a public, static factory method.
Example

In the operating system, print Spooler is an application for managing print tasks, where users can delete, abort, or change the priority of a print task, allowing only one print pool object to be run on a system and throwing an exception if the print pool is repeatedly created. A singleton mode is now used to simulate the design of the print pool.

Advantages
    • Provides controlled access to a unique instance. Because the Singleton class encapsulates its only instance, it can tightly control how and when the customer accesses it, and provides a shared concept for the design and development team.
    • Because there is only one object in system memory, system resources can be saved, and for some objects that need to be created and destroyed frequently, the singleton mode can undoubtedly improve the performance of the system.
    • Allows a variable number of instances. We can extend it based on a singleton pattern, using a similar approach to single-instance control to get a specified number of object instances.
Disadvantages
    • Because there is no abstraction layer in the singleton pattern, the expansion of the Singleton class is very difficult.
    • The responsibility of the Singleton class is too heavy, which violates the "single duty principle" to some extent. Because the Singleton class serves both as a factory role, provides a factory approach, and acts as a product role, it includes business methods that combine the creation of products with the functionality of the product itself.
    • The misuse of the singleton will bring some negative problems, such as the design of the database connection pool object as a singleton class in order to save resources, which may result in too many programs sharing connection pool objects and a connection pool overflow; Many object-oriented languages, such as Java, C #, now have a technology for automatic garbage collection, so If an instantiated object is not exploited for a long time, the system considers it to be garbage, automatically destroys and reclaims the resource, and instantiates it again the next time it is exploited, which results in the loss of the object state.
Applicable Environment

You can use Singleton mode in the following situations:

    • The system requires only one instance object, such as a system requirement to provide a unique serial number generator, or to consider that the resource consumption is too large to allow only one object to be created.
    • A single instance of the client invocation class allows only one public access point, except for that public access point, which cannot be accessed by other means.
    • Singleton mode should be used in a system where only one instance of a class is required. Conversely, if a class can have several instances to coexist, the singleton pattern needs to be improved to make it a multiple-case pattern
Mode Application

A table with an AutoNumber primary key can be used by multiple users at the same time, but there can be only one place in the database to assign the next primary key number, otherwise the primary key is duplicated, so the primary key number generator must be unique and can be implemented in singleton mode.

Summary
    • The singleton pattern ensures that a class has only one instance, and instantiates it itself and provides it to the entire system, a class called a singleton class that provides a method for global access. The main points of the singleton pattern are three: one is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own. Singleton mode is an object-creation pattern.
    • The singleton pattern contains only one singleton role: Only one instance is generated in the internal implementation of the Singleton class, and it provides a static factory method that allows the customer to use its only instance, and to prevent its constructor from being instantiated externally, it is designed to be private.
    • The purpose of the singleton pattern is to ensure that a class has only one instance and provides a global access point to access it. The Singleton class has a private constructor that ensures that the user cannot instantiate it directly with the new keyword. In addition, the schema contains a static private member variable and a static public factory method. The factory method is responsible for verifying the existence of the instance and instantiating itself, and then storing it in a static member variable to ensure that only one instance is created.
    • The main advantage of the singleton mode is that it provides controlled access to the unique instance and can conserve system resources, and its main disadvantage is that it is difficult to expand due to the lack of abstraction layer, and the single-class responsibility is too heavy.
    • The singleton mode is applicable to a system that requires only one instance object; A single instance of the client invocation class allows only one public access point.

SOURCE 1:http://design-patterns.readthedocs.org/zh_cn/latest/creational_patterns/singleton.html

SOURCE 2:http://blog.csdn.net/jason0539/article/details/23297037

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.