Two design modes (2) ==>> "single Case"

Source: Internet
Author: User

The so-called "single case":

Singleton mode is a kind of common software design pattern. In its core structure, there is only one special class that is called a singleton. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.

Examples in C #:

Ext.: http://www.cnblogs.com/xun126/archive/2011/03/09/1970807.html

First, the Classic mode:

 Public classsingleton{Private StaticSingleton instance; PrivateSingleton () {} Public StaticSingleton getinstance () {if(instance==NULL) {instance=NewSingleton (); }                returninstance; }}

The parsing is as follows:

1) First, the Singleton constructor must be private to ensure that the client program does not produce an instance through the new () operation to achieve the purpose of the singleton;

2) because the lifetime of a static variable is the same as the life cycle of the entire application, you can define a private static global variable instance to hold the unique instance of the class ;

3) You must provide a global function access to the instance, and in that function provides the ability to control the number of instances, that is, through the IF statement to determine whether the instance has been instantiated, if not, you can create an instance with new (); otherwise, return an instance directly to the customer.

4) Testing

            Singleton P1 = singleton.getinstance ();             = singleton.getinstance ();             if (P1 = = p2)            {                // will be displayed                MessageBox.Show ("The address is the same!" ");            }

In this classic mode, the thread is not considered for concurrent acquisition of the instance problem, that is, there may be two threads to obtain the instance instance at the same time, and when it is null, there will be two threads created instance, violating the singleton rule. Therefore, you need to modify the above code.

Two, multi-threaded single case mode

1. Lazy mode

 Public classsingleton{Private StaticSingleton instance; Private Static Object_lock=New Object(); PrivateSingleton () {} Public StaticSingleton getinstance () {if(instance==NULL)               {                      Lock(_lock) {if(instance==NULL) {instance=NewSingleton (); }                      }               }               returninstance; }}

The above code uses the double lock method to solve the single-mode implementation of multi-threading. First look at the inner if statement block, when using this block, the first lock operation to ensure that only one thread can access the statement block, and thus ensure that only one instance is created. Look at the outer if statement block, which allows each thread to acquire an instance without having to lock each time, because only if the instance is empty (that is, an instance needs to be created), the lock creation is required, and if an instance already exists, the instance is returned directly, saving performance overhead.

2. A Hungry man mode

This model is characterized by its own active instance.

 public  sealed  class   singleton{ private  static  readonly  Singleton instance=new           Singleton ();  private   Singleton () {} public  static   Singleton getinstance () { return<        /span> instance; }}
The ReadOnly key used above can be used with static to specify that the constant is of category level, its initialization is implemented by the static constructor, and can be compiled at run time. In this mode, there is no need to solve the thread safety problem yourself, the CLR will fix it for us.  As a result of this class being loaded, the class is automatically instantiated without having to instantiate a unique singleton object after the first call to GetInstance (). Ext.: http://www.cnblogs.com/xun126/archive/2011/03/09/1970807.html

Two design modes (2) ==>> "single Case"

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.