C#设计模式:单例模式(Singleton)
一,单例模式:它的主要特点不是根据客户程序调用生成一个新的实例,而是控制某个类型的实例数量-唯一一个,就是保证在整个应用程序的生命周期中,在任何时刻,被指定的类只有一个实例,并为客户程序提供一个获取该实例的全局访问点。
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)的更多相关文章
- 设计模式 单例模式(Singleton) [ 转载2 ]
设计模式 单例模式(Singleton) [ 转载2 ] @author java_my_life 单例模式的结构 单例模式的特点: 单例类只能有一个实例. 单例类必须自己创建自己的唯一实例. 单例类 ...
- 设计模式 单例模式(Singleton) [ 转载 ]
设计模式 单例模式(Singleton) [ 转载 ] 转载请注明出处:http://cantellow.iteye.com/blog/838473 前言 懒汉:调用时才创建对象 饿汉:类初始化时就创 ...
- JAVA设计模式-单例模式(Singleton)线程安全与效率
一,前言 单例模式详细大家都已经非常熟悉了,在文章单例模式的八种写法比较中,对单例模式的概念以及使用场景都做了很不错的说明.请在阅读本文之前,阅读一下这篇文章,因为本文就是按照这篇文章中的八种单例模式 ...
- 浅谈设计模式--单例模式(Singleton Pattern)
题外话:好久没写blog,做知识归纳整理了.本来设计模式就是个坑,各种文章也写烂了.不过,不是自己写的东西,缺少点知识的存在感.目前还没做到光看即能记住,得写.所以准备跳入设计模式这个大坑. 开篇先贡 ...
- [工作中的设计模式]单例模式singleton
一.模式解析: 单例模式是最简单和最常用的设计模式,面试的时候,不管新毕业的学生还是已经工作多年的筒子,对单例模式基本都能聊上两句.单例模式主要体现在如下方面: 1.类的构造函数私有化,保证外部不能直 ...
- 23种设计模式--单例模式-Singleton
一.单例模式的介绍 单例模式简单说就是掌握系统的至高点,在程序中只实例化一次,这样就是单例模式,在系统比如说你是该系统的登录的第多少人,还有数据库的连接池等地方会使用,单例模式是最简单,最常用的模式之 ...
- 设计模式--单例模式Singleton(创建型)
单例模式很显然是定义一个类,这个类在程序中只有唯一的实例对象.一般单例类的构造函数是私有的,只能通过调用静态函数GetInstance来获取实例. 一.单例模式有三种:懒汉式单例.饿汉式单例.登记式单 ...
- 设计模式--单例模式Singleton
单例模式顾名思义整个程序下只有一个实例,例如一个国家只有一个皇帝,一个军队只有一个将军.单例模式的书写又分为饿汉模式和懒汉模式 饿汉模式 类中代码 package demo; public cla ...
- 设计模式——单例模式(Singleton)
保证一个类仅有一个实例,并提供一个访问它的全局访问点.——DP UML类图 模式说明 个人认为单例模式是所有设计模式中最为简单的一个模式,因为实现这个模式仅需一个类,而不像其他模式需要若干个类.这个模 ...
- 设计模式-单例模式(Singleton) (创建型模式)
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码 //Singleton.h #pragma once #include<iostream> class Sin ...
随机推荐
- 简要说明 django restframework 的交互式文档
现在为了解决前后端交互沟通的问题,不少框架都推出了相关的swage库, 用起来似乎很是友好. 正好最近在开发一个小项目,想到新项目就用新版本新技术的理念,我下载了restframework 3.7的版 ...
- sublime下载emmet
Emmet是一款Web前端开发工具Sublime非常有用的插件,使用仿CSS选择器的语法来生成代码,大大提高了HTML和CSS代码编写的速度.只需按住Tab键即可把一个简写展开成HTML和CSS的代码 ...
- unixbench
1.下载 https://github.com/kdlucas/byte-unixbench/archive/v5.1.3.tar.gz 2.修改Makefile 交叉编译 #CC=gccCC = a ...
- Python之批量读取文件【面试必学】
python的os模块可以实现普遍的操作系统功能,并且和平台无关.以下为实现根目录下文件的批量读取. os.listdir(dirname)可以列出dirname下的目录和文件,依次读取相应的文件即可 ...
- 使用Fabric在tomcat中部署应用的问题总结
关闭tomcat时 A.为什么调用shutdown时,报错连接拒绝 结论——很可能是因为tomcat没启动或没完全启动:而这个时候调用shutdown就会出现此类报错 解决方法:time.sleep ...
- centos7标准版命令界面和图形界面相互切换
1.root登陆终端 2.输入命令 vi /etc/inittab ,查看两种界面的启动模式: 3.退出vi模式,,输入命令systemctl get-default 查看当前系统启动模式:我的是命令 ...
- BZOJ 1112: [POI2008]砖块Klo Splay + 性质分析
Code: #include<bits/stdc++.h> using namespace std; #define setIO(s) freopen(s".in",& ...
- 小陈现有2个任务A,B要完成,每个任务分别有若干步骤如下 一道网上没啥题解的难题(至少我是这么觉得的)
小陈现有2个任务A,B要完成,每个任务分别有若干步骤如下:A=a1->a2->a3,B=b1->b2->b3->b4->b5.在任何时候,小陈只能专心做某个任务的一 ...
- ruby在类中访问@,类外访问调用方法
class Box def initialize(w,h) @width,@height=w,h end def printWidth puts @width end def printHeight ...
- MySQL 查询性能优化 - EXPLAIN 命令
查询优化的官方文档在 这里. EXPLAIN 的输出格式 译文 1. MySQL 架构 1.1 MySQL 的简化架构 MySQL 可以简单的分为三层:连接层.服务层.存储引擎层.其中服务层包含了 M ...