Design pattern Instance Resolution-Create pattern (Singleton, Abstract Factory, Builder)

Source: Internet
Author: User

Single-piece mode (Singleton)

The so-called single piece mode, that is, in the system, a class only exists a unique instance, while providing a unique access method.

In our development, often occurs when a unique object is used, such as in web development, the object to record the number of visitors to the site, the object to which the program attributes are configured, and in network programming, only one connected object can be established, and so on, similar to these scenarios, a single piece mode is applied.

Here is an example to illustrate the use of a single piece mode, the function of the example is a program configuration information management, need to provide a configuration of the add and read methods, and only allow the creation of an instance of the configuration management class, the code is as follows:

class SingletonConfig
{
 private Dictionary<string, string> lsConfig = new Dictionary<string, string>();

 /// <summary>
 /// 私有构造函数,防止外部程序调用创建新实例
 /// </summary>
 private SingletonConfig()
 {
 }

 public void Add(string key, string value)
 {
  lsConfig.Add(key, value);
 }

 public string Get(string key)
 {
  if (lsConfig.ContainsKey(key))
  {
   return lsConfig[key];
  }
  else
  {
   return null;//也可抛出异常
  }
 }

 private static SingletonConfig _instance;
 /// <summary>
 /// 配置类实例访问对象
 /// </summary>
 public static SingletonConfig Instance
 {
  get {
   if (_instance == null)
    {
     _instance = new SingletonConfig();
    }
    return _instance;
  }
 }
}

The above code has two places to note, one is the constructor declared as a private type, which prevents the code from building a new instance through the constructor method, as the following code will cause a compiler error:

SingletonConfig s = new SingletonConfig();

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.