一,单例模式:它的主要特点不是根据客户程序调用生成一个新的实例,而是控制某个类型的实例数量-唯一一个,就是保证在整个应用程序的生命周期中,在任何时刻,被指定的类只有一个实例,并为客户程序提供一个获取该实例的全局访问点。

1,静态方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace SingletonPattern
{
public class Singleton
{
private Singleton()
{
Console.WriteLine("{0}被创建了,线程ID{1}!", this.GetType().Name, Thread.CurrentThread.ManagedThreadId);
} public static Singleton _singleton = null;
public static object lockObject = new object();
/// <summary>
///创建实例
/// </summary>
/// <returns></returns>
public static Singleton CreateIntance()
{
if (_singleton == null) //保证对象初始化之后的所有线程,不需要等待锁
{
Console.WriteLine("准备进入Lock");
lock (lockObject) //保证只有一个进程去判断
{
if (_singleton == null) //保证为空才正的创建
{
_singleton = new Singleton();
}
}
}
return _singleton;
} public void Show()
{
Console.WriteLine("显示!!!");
}
}
}

2,静态构造单例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace SingletonPattern
{
public class SingletonSecond
{
public static SingletonSecond _singleton = null;
private SingletonSecond()
{
Console.WriteLine("{0}被创建了,线程ID{1}!", this.GetType().Name,Thread.CurrentThread.ManagedThreadId);
}
/// <summary>
///1,静态构造函数:由CLR保证,再第一次使用这个类型之前,调用而且之调用一次
/// </summary>
/// <returns></returns>
static SingletonSecond()
{
_singleton = new SingletonSecond();
}
public static SingletonSecond CreateIntance()
{
return _singleton;
} public void Show()
{
Console.WriteLine("显示!!!");
}
}
}

3,静态变量单例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace SingletonPattern
{
public class SingletonThird
{ private SingletonThird()
{
Console.WriteLine("{0}被创建了,线程ID{1}!", this.GetType().Name,Thread.CurrentThread.ManagedThreadId);
}
/// <summary>
/// 静态变量:会在类型第一次使用的时候初始化,而且只初始化一次
/// </summary>
private static SingletonThird _singleton = new SingletonThird();
public static SingletonThird CreateIntance()
{
return _singleton;
} public void Show()
{
Console.WriteLine("显示!!!");
}
}
}

4,输出结果

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace SingletonPattern
{
/// <summary>
/// 单例模式
/// 保证整个进程中该对象只被实例化一次,常驻内存,根据这个特点:单例模式有三种写法:Singleton,SingletonSecond,SingletonThird,
/// 普通的类型是需要的时候初始化,使用完被GC回收,跟静态不一样
/// </summary>
class Program
{
static void Main(string[] args)
{
//Singleton singleton = Singleton.CreateIntance();
//for (int i = 0; i < 10; i++)
//{
// Singleton singleton = Singleton.CreateIntance();
// singleton.Show();
//}
Console.WriteLine("---------------------------------------");
//多线程测试调用,结果也是公用一个对象,之调用一次构造函数
List<IAsyncResult> asyncResults = new List<IAsyncResult>();
for (int i = ; i < ; i++)
{
asyncResults.Add(new Action(() =>
{
Singleton singleton = Singleton.CreateIntance();
singleton.Show();
}).BeginInvoke(null,null)); //会启动一个异步多线程的调用
} ////判断多线程是否执行完了
while (asyncResults.Count(r => !r.IsCompleted) > )
{
Thread.Sleep();
} Console.WriteLine("---------------------------------------");
//多线程测试调用,结果也是公用一个对象,之调用一次构造函数
List<IAsyncResult> asyncResults2 = new List<IAsyncResult>();
for (int i = ; i < ; i++)
{
asyncResults2.Add(new Action(() =>
{
SingletonSecond singleton = SingletonSecond.CreateIntance();
singleton.Show();
}).BeginInvoke(null, null)); //会启动一个异步多线程的调用
} ////判断多线程是否执行完了
while (asyncResults2.Count(r => !r.IsCompleted) > )
{
Thread.Sleep();
} Console.WriteLine("---------------------------------------");
List<IAsyncResult> asyncResults3 = new List<IAsyncResult>();
for (int i = ; i < ; i++)
{
asyncResults3.Add(new Action(() =>
{
SingletonThird singleton = SingletonThird.CreateIntance();
singleton.Show();
}).BeginInvoke(null, null)); //会启动一个异步多线程的调用
}
Console.ReadKey();
}
}
}

得到的结果都是一样的,共有对象,都是被构造一次

二,单例模式的扩展

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _1_2单例模式
{
class Program
{
static void Main(string[] args)
{
Demo.Instance.Say();
}
} public class SingleTon<T> where T : new()
{
private static T _instance;
public static T Instance
{
get { return _instance = new T(); }
}
} public class Demo : SingleTon<Demo>
{
public void Say()
{
Console.WriteLine("单例模式");
}
}
}

三:单例模式(Singleton)的特点

1,私有构造函数,原因使用者不可以实例,则单例模式全局只有一个实例

2,静态实例,因为静态变量的生命周期跟整个应用程序的生命周期是一样的,所以定义一个私有的静态全局变量instance来保存该类的唯一实例;

3,单例模式避免多线程并发造成实例并不唯一,则需要用到锁。锁的解析如以上代码。

C#设计模式:单例模式(Singleton)的更多相关文章

  1. 设计模式 单例模式(Singleton) [ 转载2 ]

    设计模式 单例模式(Singleton) [ 转载2 ] @author java_my_life 单例模式的结构 单例模式的特点: 单例类只能有一个实例. 单例类必须自己创建自己的唯一实例. 单例类 ...

  2. 设计模式 单例模式(Singleton) [ 转载 ]

    设计模式 单例模式(Singleton) [ 转载 ] 转载请注明出处:http://cantellow.iteye.com/blog/838473 前言 懒汉:调用时才创建对象 饿汉:类初始化时就创 ...

  3. JAVA设计模式-单例模式(Singleton)线程安全与效率

    一,前言 单例模式详细大家都已经非常熟悉了,在文章单例模式的八种写法比较中,对单例模式的概念以及使用场景都做了很不错的说明.请在阅读本文之前,阅读一下这篇文章,因为本文就是按照这篇文章中的八种单例模式 ...

  4. 浅谈设计模式--单例模式(Singleton Pattern)

    题外话:好久没写blog,做知识归纳整理了.本来设计模式就是个坑,各种文章也写烂了.不过,不是自己写的东西,缺少点知识的存在感.目前还没做到光看即能记住,得写.所以准备跳入设计模式这个大坑. 开篇先贡 ...

  5. [工作中的设计模式]单例模式singleton

    一.模式解析: 单例模式是最简单和最常用的设计模式,面试的时候,不管新毕业的学生还是已经工作多年的筒子,对单例模式基本都能聊上两句.单例模式主要体现在如下方面: 1.类的构造函数私有化,保证外部不能直 ...

  6. 23种设计模式--单例模式-Singleton

    一.单例模式的介绍 单例模式简单说就是掌握系统的至高点,在程序中只实例化一次,这样就是单例模式,在系统比如说你是该系统的登录的第多少人,还有数据库的连接池等地方会使用,单例模式是最简单,最常用的模式之 ...

  7. 设计模式--单例模式Singleton(创建型)

    单例模式很显然是定义一个类,这个类在程序中只有唯一的实例对象.一般单例类的构造函数是私有的,只能通过调用静态函数GetInstance来获取实例. 一.单例模式有三种:懒汉式单例.饿汉式单例.登记式单 ...

  8. 设计模式--单例模式Singleton

    单例模式顾名思义整个程序下只有一个实例,例如一个国家只有一个皇帝,一个军队只有一个将军.单例模式的书写又分为饿汉模式和懒汉模式 饿汉模式   类中代码 package demo; public cla ...

  9. 设计模式——单例模式(Singleton)

    保证一个类仅有一个实例,并提供一个访问它的全局访问点.——DP UML类图 模式说明 个人认为单例模式是所有设计模式中最为简单的一个模式,因为实现这个模式仅需一个类,而不像其他模式需要若干个类.这个模 ...

  10. 设计模式-单例模式(Singleton) (创建型模式)

    //以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码 //Singleton.h #pragma once #include<iostream> class Sin ...

随机推荐

  1. CSS3 nth-of-type(n)选择器 last-of-type选择器 nth-last-of-type(n)选择器 CSS3 only-child选择器 only-of-type选择器

    CSS3 nth-of-type(n)选择器 “:nth-of-type(n)”选择器和“:nth-child(n)”选择器非常类似,不同的是它只计算父元素中指定的某种类型的子元素.当某个元素中的子元 ...

  2. bzoj4771 七彩树 dfs序+主席树+树链的并

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=4771 题解 一道不错的树链并的基础练习题. 如果不是树,而是一个数组的话,对于给定区间内的不同 ...

  3. java File过滤文件的多种方法

    package com.qf.part1; import java.io.File; import java.io.FileFilter; import java.io.IOException; pu ...

  4. Python配置模块:configparser参数含义

    https://blog.csdn.net/CoderPai/article/details/80420698

  5. C指针,&,*,指针的指针

    C指针: 指向变量的地址,想象成房间号 &: 取地址符号 *:间接访问符号, 访问p所存地址的内容 #include <iostream> int main(int argc, c ...

  6. 四-1、Cadence Allegro推荐操作方式和视图命令

    第四章:实用命令详解 1.Cadence Allegro推荐操作方式: 激活命令 选择操作对象的属性 设置相关的命令参数 单击对应的对象 结束命令 2.视图命令:

  7. Android 中的 Matrix

    Matrix 是 Android SDK 提供的一个矩阵类,它代表一个 3 X 3 的矩阵 Matrix主要可以对图像做4种基本变换 Translate 平移变换 Rotate 旋转变换 Scale ...

  8. 整数解 (hdu 2092

    整数解 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  9. 攻防世界 | string

    #encoding=utf-8 #!usr/bin/python from pwn import * io = remote('111.198.29.45',42643) io.recvuntil(& ...

  10. 学习日记12、list集合中根据某个字段进行去重复操作

    List<T_CusBankCardInfoModel> blist = B_BLL.GetListByCusId(CusIds).Distinct(new ModelComparer() ...