定义:
Singleton模式主要作用是保证在应用程序中,一个类只有一个实例存在。
原理:
将目标类的构造函数私有化,因此只能被类本身创建。
下面是Singleton模式的原型:
namespace UI |
{ |
public class Singleton |
{ |
private Singleton() { } |
|
private static Singleton instance = null; |
|
public static Singleton GetInstance() |
{ |
if (instance == null) |
instance = new Singleton(); |
|
return instance; |
} |
} |
} |
下面来验证这样写是否真的起作用了,我们添加一个Info属性:
namespace UI |
{ |
public class Singleton |
{ |
private Singleton() { } |
|
private static Singleton instance = null; |
|
public string Info { get; set; } |
|
public static Singleton GetInstance(string info) |
{ |
if (instance == null) |
instance = new Singleton { Info = info }; |
|
return instance; |
} |
} |
} |
这样,如果成功的话,Info属性只能被赋值一次,下面是测试入口代码:
using System; |
|
namespace UI |
{ |
public class Program |
{ |
public static void Main(string[] args) |
{ |
Singleton myS1 = Singleton.GetInstance("Success once"); |
Singleton myS2 = Singleton.GetInstance("Success twice"); |
|
Console.Title = "Singleton test"; |
Console.WriteLine(myS1.Info); |
Console.WriteLine(myS2.Info); |
|
Console.ReadLine(); |
} |
} |
} |
如果成功的话,两次都会输出“Success once”,
本文详细介绍了Singleton模式的概念及其在C#中的实现方式,并通过一个简单的示例验证了该模式能够确保一个类仅有一个实例存在。

1541

被折叠的 条评论
为什么被折叠?



