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();