设计模式C#实现(六)——单例模式
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
构成:
1.私有的构造函数
2.私有静态的实例
3.返回实例的静态方法
public class Singleton
{
private static Singleton uniqueInstance = new Singleton();
private Singleton() { Console.WriteLine("this is a new singleton"); }
public static Singleton getInstance()
{
if (uniqueInstance == null)
{
return uniqueInstance;
}
return uniqueInstance;
}
}
这种叫做饿汉模式,实例在类加载时就创建了,缺点是如果实例如果消耗大量的资源而没有使用就会造成浪费,另一种懒汉模式,实例在被使用时才创建,
public class Singleton
{
private static Singleton uniqueInstance;
private Singleton() { Console.WriteLine("this is a new singleton"); }
public static Singleton getInstance()
{
if (uniqueInstance == null)
{
return uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
但是这不是线程安全的
例如
class Program {
static void Main(string[] args) {
while (true) {
Thread t1 = new Thread(Test);
t1.Start();
}
}
static void Test() {
Singleton s = Singleton.getInstance();
}
}
执行的结果有可能是这样

程序创建了多个实例,这不是我们想要的结果,原因是某个线程if (uniqueInstance == null)语句执行后让出了使用权,当它重新获得CPU使用权的时候,可能别的CPU已经创建了实例,而它并不知道,继续执行return uniqueInstance= new Singleton();导致出现多个实例。
因此,要为方法加锁
public class Singleton
{
private static Singleton uniqueInstance;
private Singleton() { Console.WriteLine("this is a new singleton"); }
private static readonly object syncRoot = new object();
public static Singleton getInstance()
{
lock (syncRoot)
{
if (uniqueInstance == null)
{
return uniqueInstance = new Singleton();
}
} return uniqueInstance;
}
}
但是这又带来了一个问题,在实例已经创建完成了,但还是会有大量的线程卡在lock (syncRoot),它们都还会尝试创建实例,这降低了性能
为此,还要为此方法创建另外一个验证
public static Singleton getInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
{
return uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
此时,当实例已经创建完成之后,各线程不再访问临界区,提高了性能
单例模式和静态类的比较
1.单例模式可以懒加载,静态类执行更快(为什么?),即在不同条件下二者有不同的性能表现
2.单例可以继承和override
3.单例易于模拟,利于测试
4.单例利于维护状态信息
update:
1.静态类执行更快?
因为静态类在编译时绑定(什么是编译时绑定?)
- Singleton object stores in Heap but, static object stores in stack
- We can clone the object of Singleton but, we can not clone the static class object
- Singleton class follow the OOP(object oriented principles) but not static class
- we can implement interface with Singleton class but not with Static class.
A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.
A static class allows only static methods.
设计模式C#实现(六)——单例模式的更多相关文章
- Java并发程序设计(八)设计模式与并发之单例模式
设计模式与并发之单例模式 简单的单例实现: public class Singleton { private Singleton(){ System.out.println("Creatin ...
- Java 设计模式系列(六)适配器模式
Java 设计模式系列(六)适配器模式 适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作. 适配器模式的结构: 类的适配器模式 对象 ...
- 设计模式(一)单例模式:创建模式 ASPNET CORE WEB 应用程序的启动 当项目中 没有STARTUP.CS 类如何设置启动 配置等等
设计模式(一)单例模式:创建模式 先聊一下关于设计的几个原则(1)单一原则(SRP):一个类应该仅有一个引起它变化的原因 :意思就是 (一个类,最好只负责一件事情,并且只有一个引起它变化的原因(2)开 ...
- 设计模式(一)单例模式(Singleton Pattern)
一.引言 最近在设计模式的一些内容,主要的参考书籍是<Head First 设计模式>,同时在学习过程中也查看了很多博客园中关于设计模式的一些文章的,在这里记录下我的一些学习笔记,一是为了 ...
- JAVA设计模式(6:单例模式详解)
单例模式作为一种创建型模式,在日常开发中用处极广,我们先来看一一段代码: // 构造函数 protected Calendar(TimeZone var1, Locale var2) { this.l ...
- PHP设计模式(四)单例模式(Singleton For PHP)
今天讲单例设计模式,这种设计模式和工厂模式一样,用的非常非常多,同时单例模式比较容易的一种设计模式. 一.什么是单例设计模式 单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时,单例对 ...
- .NET设计模式(1):1.1 单例模式(Singleton Pattern)
概述 单例模式就是保证在整个应用程序的生命周期中,在任何时刻,被指定的类只有一个实例,并为客户程序提供一个获取该实例的全局访问点. 单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单 ...
- java设计模式(四)--单例模式
Singleton最熟悉不过了,下面学习单例模式.转载:http://zz563143188.iteye.com/blog/1847029 单例对象(Singleton)是一种常用的设计模式.在Jav ...
- Java设计模式学习笔记(单例模式)
最近一直在看<Head First设计模式>,这本书写的确实是很不错的,专注于怎么用最简单的方式最通俗的语言让人了解设计模式.据说GoF的设计模式那本书写的很好,是一本经典,但是就是难懂, ...
随机推荐
- [C#高级编程]基础知识摘要一
核心C#: 值类型存储在堆栈中,而引用类型存储在托管堆上. object类型可以用于两个目的: 可以使用object引用绑定任何子类型的对象 object类型执行许多一般用途的基本方法,包括Equal ...
- Gradle学习系列之十——自定义Plugin(本系列完)
在本系列的上篇文章中,我们讲到了如何自定义Task类型,在本篇文章中,我们将讲到如何自定义Plugin. 请通过以下方式下载本系列文章的Github示例代码: git clone https://gi ...
- thread_fork/join并发框架1
一.线程并发控制 Thread.Executor.ForkJoin和Actor 1.裸线程 Runnable接口,调用.start()开始,没有现成的API来结束线程,你需要自己来实现, ...
- Import 元素 (MSBuild)
Import 元素 (MSBuild) Visual Studio 2013 .NET Framework 4 .NET Framework 3 ...
- PHP的加密解密字符串函数
程序中经常使用的PHP加密解密字符串函数 代码如下: /********************************************************************* 函数 ...
- 【jQuery基础学习】06 jQuery表单验证插件-Validation
jQuery的基础部分前面都讲完了,那么就看插件了. 关于jQuery表单验证插件-Validation validation特点: 内置验证规则:拥有必填.数字.E-Mail.URL和信用卡号码等1 ...
- 使用layout_weight设置控件占屏幕百分比
水平LinearLayout中如果A,B两个控件都是layout_weight="1",那么控件在水平方向占比为A的layout_width+1/2空闲空间,B的layout_wi ...
- 泛函编程(13)-无穷数据流-Infinite Stream
上节我们提到Stream和List的主要分别是在于Stream的“延后计算“(lazy evaluation)特性.我们还讨论过在处理大规模排列数据集时,Stream可以一个一个把数据元素搬进内存并且 ...
- 那些教程没有的php2-对象
php.net 对象 在类定义内部,可以用 new self 和 new parent 创建新对象. 当把一个对象已经创建的实例赋给一个新变量时,新变量会访问同一个实例,就和用该对象赋值一样.可以用克 ...
- 在Hadoop平台跑python脚本
1.开发IDE,我使用的是PyCharm. 2.运行原理 使用python写MapReduce的“诀窍”是利用Hadoop流的API,通过STDIN(标准输入).STDOUT(标准输出)在 ...