C # Design Pattern Series Tutorials-Single case mode _c# tutorial

Source: Internet
Author: User

1. Description:

Guarantees that a class has only one instance and provides a global access point to access it.

2. The single case model has 3 main features:

2.1 Singleton classes Ensure that you have only one instance.
2.2 The Singleton class must create its own instance.
The 2.3 Singleton class must provide a unique instance for other objects.

3. Implementation: Lazy single case class and a hungry man single case class

3.1 Lazy Single Case class
For the lazy model, we can understand this: the single class is very lazy, only when they need to act, never know to prepare early. It determines whether an object already exists when it is in need of an object, creates an object immediately if it is not, and returns if an existing object is no longer created.
Lazy mode is created only when an external object requests the instance for the first time.

3.2 A hungry man type single case
For a hungry man mode, we can understand that the single example class is very hungry and desperately needs to eat, so it creates objects immediately when the class loads.

3.3 The pros and cons of the lazy and a hungry man models:
Lazy mode, it is characterized by the runtime to get objects slow, but load the class faster. It takes up only a fraction of the time in the entire application lifecycle.
A hungry man mode, it is characterized by loading the class is slow, but the runtime to get objects faster. It will always occupy resources from the time it is loaded to the end of the application.
These two models for faster initialization, less resource-intensive lightweight objects, there is not much performance difference, choose the lazy or a hungry man-style is no problem. But for the initialization is slow, occupy the resources of heavy objects, there will be a more obvious difference. Therefore, the application of a hungry man mode to the heavyweight object, class loading is slow, but the speed is fast; Lazy mode in contrast, class loading is fast, but the first time the runtime to get objects slow.
From the user experience point of view, we should prefer the A hungry man mode. We are willing to wait for a program to take a long time to initialize, but do not like to wait too long while the program is running, giving a sense of insensitivity, so we recommend using the A Hungry man mode for a single case pattern with heavy object participation.
For lightweight objects that are initialized faster, it's OK to choose which method to use. If a large number of single case patterns are used in an application, we should weigh the two methods. Lightweight objects with a single example of lazy mode, reduce load burden, shorten the loading time, improve the loading efficiency; At the same time, because it is a lightweight object, the creation of these objects in the use of, in fact, the creation of a single example objects consumed by the time allocated to the entire application, for the entire application of the operational efficiency has not greatly affected.

4. Code implementation:

4.1 Lazy Type

  public class Singleton
  {
    private static Singleton m_instance;

    Private Singleton ()
    {
      //The default constructor is defined as private to prevent external invocation of it to instantiate other objects
    } public

    static Singleton getinstance ()
    {

      if (m_instance = null)
      {
        m_instance = new Singleton ();
      }

      Return m_instance
    }
  }

4.2 A Hungry man type

  defined as sealed to prevent derivation because the derivation may increase the instance public
  sealed class Singleton
  {
    private static readonly Singleton m_ Instance = new Singleton ();
    Private Singleton ()
    {
      //The default constructor is defined as private to prevent external invocation of it to instantiate other objects
    } public

    static Singleton getinstance ()
    {return
      m_instance;
    }
  }

5. Model Summary

5.1 Advantages:
Prevents the instantiation of multiple objects in the application. This saves overhead, each instance taking up a certain amount of memory, and it takes time and space to create the object.

5.2 Disadvantages:

5.3 Applicable occasions:
5.3.1 control the use of resources, through thread synchronization to control the concurrent access of resources;
The 5.3.2 control instance produces the quantity, achieves saves the resources the goal.
5.3.3 is used as a communication medium, that is, data sharing, which enables communication between multiple unrelated two threads or processes without establishing a direct association.

5.4 Support for design principles:

One of the most important aspects of using a single case pattern is the "single responsibility" principle in object-oriented encapsulation.

6. Add: In the multithreaded opening process, it is possible to prevent two threads from instantiating objects at the same time in the use of the Lazy singleton mode.

Here are the solutions

6.1 Use the lock mechanism

  public class Singleton
  {
    private static Singleton m_instance;

    Static readonly Object o = new Object ();

    Private Singleton ()
    {
      //The default constructor is defined as private to prevent external invocation of it to instantiate other objects
    } public

    static Singleton getinstance ()
    {
      Lock (o)
      {
        if (m_instance = = null)
        {
          m_instance = new Singleton ();
        }
      }

      Return m_instance
    }
  }

Using a lock mechanism prevents two threads from creating objects at the same time, but there is a performance problem, and whenever a thread accesses the getinstance () This method is to lock it up, which is actually unnecessary.

6.2 Double Lock

  public class Singleton
  {
    private static Singleton m_instance;

    Static readonly Object o = new Object ();

    Private Singleton ()
    {
      //The default constructor is defined as private to prevent external invocation of it to instantiate other objects
    } public

    static Singleton getinstance ()
    {
      //Here is a decision to determine whether an instance exists, only to lock it if it does not exist, that is, to add only one lock
      if (m_instance = null)
      {
        lock (o)
        {) In the life cycle of this instance.
          if (m_instance = null)
          {
            m_instance = new Singleton ();

      }}} Return m_instance
    }
  }

Double locking guarantees that an instance is locked only once in its lifecycle, so it has no effect on performance.

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.