21
5
内容纲要

单件模式属于创建型模式,创造性模式主要是关注于如何以及何时创建对象。Singleton 模式可以保证一个类有且只有一个实例,并提供一个访问它的全局访问点。在程序设计过程中,有很多情况需要确保一个类只能有一个实例。

namespace Singleton.Design.Pattern
{
class Program
{
static void Main(string[] args)
{
//Singleton e = new Singleton(); 这是错误的,因为已经设定为保护类型了
Singleton instance = Singleton.Instance();
instance.Show();
Console.ReadKey();
}
}
public class Singleton
{
private static Singleton instance;
protected Singleton()
{
}
public static Singleton Instance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
public void Show()
{
Console.WriteLine("Singleton is Show now!");
}
}
}

声明: 本文采用 BY-NC-SA 协议进行授权. 未标注“转”的文章均为原创,转载请注明转自: 设计模式:单件模式C#实现,源代码

公告栏

欢迎大家来到我的博客,我是dodoro,希望我的博客能给你带来帮助。