1、非线程安全(经典模式),但没有考虑线程安全,在多线程时可能会出问题,不过还从没看过出错的现象。

/// <summary>
/// 单例模式的实现
/// </summary>
public class Singleton
{
// 定义一个静态变量来保存类的实例
private static Singleton uniqueInstance; // 定义私有构造函数,使外界不能创建该类实例
private Singleton()
{
} /// <summary>
/// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// 如果类的实例不存在则创建,否则直接返回
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}

2、简单安全线程

/// <summary>
/// 单例模式的实现
/// </summary>
public class Singleton
{
// 定义一个静态变量来保存类的实例
private static Singleton uniqueInstance; // 定义一个标识确保线程同步
private static readonly object locker = new object(); // 定义私有构造函数,使外界不能创建该类实例
private Singleton()
{
} /// <summary>
/// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// 当第一个线程运行到这里时,此时会对locker对象 "加锁",
// 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁
// lock语句运行完之后(即线程运行完之后)会对该对象"解锁"
lock (locker)
{
// 如果类的实例不存在则创建,否则直接返回
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
} return uniqueInstance;
}
}

上面这种解决方案确实可以解决多线程的问题,但是上面代码对于每个线程都会对线程辅助对象locker加锁之后再判断实例是否存在,对于这个操作完全没有必要的,因为当第一个线程创建了该类的实例之后,后面的线程此时只需要直接判断(uniqueInstance==null)为假,此时完全没必要对线程辅助对象加锁之后再去判断,所以上面的实现方式增加了额外的开销,损失了性能,为了改进上面实现方式的缺陷,我们只需要在lock语句前面加一句(uniqueInstance==null)的判断就可以避免锁所增加的额外开销,这种实现方式我们就叫它 “双重锁定”,下面是具体实现代码:

3、尝试线程安全(双重锁定)

  /// <summary>
/// 单例模式的实现
/// </summary>
public class Singleton
{
// 定义一个静态变量来保存类的实例
private static Singleton uniqueInstance; // 定义一个标识确保线程同步
private static readonly object locker = new object(); // 定义私有构造函数,使外界不能创建该类实例
private Singleton()
{
} /// <summary>
/// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// 当第一个线程运行到这里时,此时会对locker对象 "加锁",
// 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁
// lock语句运行完之后(即线程运行完之后)会对该对象"解锁"
// 双重锁定只需要一句判断就可以了
if (uniqueInstance == null)
{
lock (locker)
{
// 如果类的实例不存在则创建,否则直接返回
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

4、饿汉模式(这种模式的特点是自己主动实例。)

public sealed class Singleton
{
private static readonly Singleton instance=new Singleton(); private Singleton()
{
} public static Singleton GetInstance()
{
return instance;
}
}

5、不完全lazy,但是线程安全且不用锁。

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton(); // 显示的static 构造函数
//没必要标记类型 - 在field初始化以前
static Singleton()
{
} // 定义私有构造函数,使外界不能创建该类实例
private Singleton()
{
} public static Singleton Instance
{
get
{
return instance;
}
}
}

6、完全延迟实例化

public sealed class Singleton
{
private Singleton()
{
} public static Singleton Instance { get { return Nested.instance; } } private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
} internal static readonly Singleton instance = new Singleton();
}
}

7、使用 .NET 4's Lazy<T> 类型

public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton()
{
}
}

详细内容介绍见网址:http://csharpindepth.com/Articles/General/Singleton.aspx#unsafe

C# 语句中的各种单例模式代码的更多相关文章

  1. SQL语句在查询分析器中可以执行,代码中不能执行

    问题:SQL语句在查询分析器中可以执行,代码中不能执行 解答:sql中包含数据库的关键字,将关键字用[]括起来,可以解决. 后记:建数据库的时候尽量避免使用关键字. 例子: sql.Format(&q ...

  2. java中异常抛出后代码还会继续执行吗

    今天遇到一个问题,在下面的代码中,当抛出运行时异常后,后面的代码还会执行吗,是否需要在异常后面加上return语句呢? public void add(int index, E element){ i ...

  3. LINQ语句中的.AsEnumerable() 和 .AsQueryable()的区别

    LINQ语句中的.AsEnumerable() 和 .AsQueryable()的区别 在写LINQ语句的时候,往往会看到.AsEnumerable() 和 .AsQueryable() .例如: s ...

  4. 【转】Java中try catch finally语句中含有return语句的执行情况(总结版)

    Java中try catch finally语句中含有return语句的执行情况(总结版) 有一点可以肯定,finally块中的内容会先于try中的return语句执行,如果finall语句块中也有r ...

  5. java中异常抛出后代码是否会继续执行

    为了回答这个问题,我编写了几段代码测试了一下,结果如下:  代码1:throw new Exception("参数越界");   System.out.println(" ...

  6. MySql的like语句中的通配符:百分号、下划线和escape

      MySql的like语句中的通配符:百分号.下划线和escape   %:表示任意个或多个字符.可匹配任意类型和长度的字符. Sql代码 select * from user where user ...

  7. [转]sql语句中出现笛卡尔乘积 SQL查询入门篇

    本篇文章中,主要说明SQL中的各种连接以及使用范围,以及更进一步的解释关系代数法和关系演算法对在同一条查询的不同思路. 多表连接简介 在关系数据库中,一个查询往往会涉及多个表,因为很少有数据库只有一个 ...

  8. Sqlserver 存储过程中结合事务的代码

    Sqlserver 存储过程中结合事务的代码  --方式一 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ ...

  9. 向已写好的多行插入sql语句中添加字段和值

    #region 添加支款方式--向已写好的多行插入sql语句中添加字段和值 public int A_ZhifuFS(int diqu) { ; string strData = @"SEL ...

随机推荐

  1. python数据结构-如何统计序列中元素的频度

    如何统计序列中元素的频度 问题举例 如何找出随机序列[1, 5, 6, 5, 3, 2, 1, 0, 6, 1, 6]中出现频度最高的3个元素? 如何统计某篇英文文章中词频最高的5个单词? 将序列转换 ...

  2. Python类中的__init__() 和 self 的解析

    原文地址https://www.cnblogs.com/ant-colonies/p/6718388.html 1.Python中self的含义 self,英文单词意思很明显,表示自己,本身. 此处有 ...

  3. 微信内置安卓x5浏览器请求超时自动重发问题处理小记

    X5内核  请求超时后会自动阻止请求返回并由代理服务器将原参数重新发送请求到服务层代码.但由于第一次请求已经请求到服务器,会导致出现重复下单.支付等重大问题. 该问题由于腾讯x5浏览器会自动阻止第一次 ...

  4. linux终端使用ss代理

    title: linux终端使用ss代理 date: 2017-11-09 21:06:16 tags: linux categories: linux 系统为archlinux 先将ss代理转化为h ...

  5. q次询问,每次给一个x,问1到x的因数个数的和。

    q次询问,每次给一个x,问1到x的因数个数的和. #include<cmath> #include<cstdio> #include<cstring> usingn ...

  6. Hdu2039 三角形

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2039 三角形 Time Limit: 2000/1000 MS (Java/Others)    Me ...

  7. 158A Next Round

    A. Next Round time limit per test 3 seconds memory limit per test 256 megabytes input standard input ...

  8. axios的封装

    function axios(options){ var promise = new Promise((resolve,reject)=>{ var xhr = null; if(window. ...

  9. go语言切片切片与指针

    go语言 1.切片的定义 切片不是真正意义上的动态数组,是引用类型. var arraySlice []int

  10. hiho一下 第168周

    题目1 : 扩展二进制数 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 我们都知道二进制数的每一位可以是0或1.有一天小Hi突发奇想:如果允许使用数字2会发生什么事情? ...