The Singleton pattern is used when you need one, and only one instance of your class. Sometimes you see this pattern used in cases where the construction of a class is expensive (like a file stream). It can be lazy loaded (at runtime instead of compiletime) and must be thread-safe. The class gets a public method or property named Instance, responsible for creating the Singleton. The constructor of the Singleton class is private, so no one can construct a new instance from the class by applying ‘new’.
using System;
namespace Singleton
{
class Program
{
static void Main(string[] args)
{
// Lazy loaded object
// Singleton gets created on first call
Singleton.Instance.SomeProperty = 0;
Singleton.Instance.SomeMethod();
}
}
public class Singleton
{
// Private constructor to prevent 'new'
private Singleton()
{
}
// The instance read only property
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
// Nested class with the actual Singleton object
private class Nested
{
internal static readonly Singleton instance =
new Singleton();
static Nested()
{
}
}
// Additional methods and propeties
public int SomeProperty { get; set; }
public void SomeMethod() { }
}
}
分享到:
相关推荐
一个java线程安全的单例模式:饥饿模式和延迟加载
Laravel开发-singleton-pattern 帮助程序包来实现单例类。
C#设计模式(7)-Singleton Pattern C#设计模式(6)-Abstract Factory Pattern C#设计模式(5)-Factory Method Pattern C#设计模式(4)-Simple Factory Pattern C#设计模式(3) - 设计原则(2) C#设计模式(2...
前端大厂最新面试题-Singleton Pattern.docx
akka-cluster-singleton-example Akka Cluster - 单例使用示例
singleton pattern 的定义 主要应用方法 优缺点 通过代码 具体分析解释
Singleton pattern单例模式应用
perl-Class-Singleton-1.4-6.el6.noarch.rpm perl-Class-Singleton-1.4-6.el6.noarch.rpm
NULL 博文链接:https://linxingliang.iteye.com/blog/1217811
示例 TypeScript 单例模式查看教程在 关于如何使用这些文件。 请务必查看我所有的。
资源来自pypi官网。 资源全名:dask-actor-singleton-1.1.0.tar.gz
简单的单例模式团队丹尼斯·卡拉赞斯莱昂纳多·派瓦鲁道夫·迪亚斯图利奥·菲利普 它是什么? Development > Organization > Good practices > Standards... SSP 是一种模块化和组织项目的简单方法。...
Java据说有23种设计模式,Android的设计模式肯定是由Java来引申出来的。这里不讨论有多少人全会,有多少种设计模式会使用到,我们来讲下其中用得最多的也就是人人都知道的...这里是一个简单的SingletonPatternDemo。
工厂三兄弟之抽象工厂模式(二) 工厂三兄弟之抽象工厂模式(三) 工厂三兄弟之抽象工厂模式(四) 工厂三兄弟之抽象工厂模式(五) 单例模式-Singleton Pattern 确保对象的唯一性——单例模式 (一) 确保对象的...
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个...
设计模式-Singleton与Factory
提供简单易懂的单件设计模式源码,为你学习这种模式提供更好捷径.
4、单例模式(Singleton Pattern) 用意:仅允许生成一个对象时
该存储库是有关用Unity3D C#编写的出色设计模式的。 现在,此存储库中的Unity3D中已经完成了23个 。 每个模式都包含相应的结构实现,应用程序示例和图表。 与,在此存储库中,每个模式都包含在一个单独的文件夹中...
Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现