Interpreting design Patterns----Single case mode (Singleton pattern)

Source: Internet
Author: User
Tags constructor

A singleton pattern guarantees that a class has and has only one instance, and provides a global access point to access it. In programming, there are many situations where you have to make sure that a class can have only one instance. From this sentence can be seen, The core of the singleton pattern: how to control any invocation of a user using new to an instance constructor of a class. How do you bypass conventional constructors and provide a mechanism to ensure that a class has only one instance? This should be the responsibility of the Class Designer rather than the user.

First, the single case pattern intention

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

A UML diagram of a single case pattern (the diagram to http://www.dofactory.com/)

Example explanation single case mode

Take a look at the following simple example:

1namespace Designpattern.singleton
2{
3 public class Singleton
4 {
5//Static private property
6 private static Singleton instance;
7
8///<summary>
9///Private constructor--Let the class's consumer not call this constructor
ten///</summary>
private Single Ton () in the public
static Singleton Instance {

  
   18 if (instance = = null)
{
instance = new Singleton ();
return to instance;//returns always the first instance of the object}
27//test class C27/>28 class Testsingleton
{public
static void Main2 (string[] args) Singl
Eton t1 = singleton.instance;
Singleton t2 = singleton.instance;
Console.WriteLine (object. ReferenceEquals (t1, t2) = = true);
}
37}
  

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.