zoukankan
html css js c++ java
C#设计模式:Singleton模式
如何保证一个类只能有一个实例存在?
在多线程情况下如何解决?
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
Singleton
{
class
Singleton
{
//
构造函数私有化,保证不被显式实例化
private
Singleton()
{ }
//
定义属性,返回Singleton对象
private
static
Singleton singleton;
public
static
Singleton Instance
{
get
{
if
(singleton
==
null
)
singleton
=
new
Singleton();
return
singleton;
}
}
}
}
//
多线程版本的Singleton
namespace
SingletonMultiThread
{
class
Singleton
{
private
static
object
lockHelper
=
new
object
();
//
构造函数私有化,保证不被显式实例化
private
Singleton()
{}
//
定义属性,返回Singleton对象
private
static
volatile
Singleton singleton
=
null
;
public
static
Singleton Instance
{
get
{
if
(singleton
==
null
)
{
lock
(lockHelper)
{
if
(singleton
==
null
)
singleton
=
new
Singleton();
}
}
return
singleton;
}
}
}
}
//
经典的Singleton实现:仅仅适合无参构造器对象(可用属性实现扩展)
namespace
classicalSingleton
{
sealed
class
Singleton
{
private
Singleton()
{ }
//
内联初始化,后面的new是个静态构造器
public
static
readonly
Singleton Instance
=
new
Singleton();
}
class
Program
{
static
void
Main(
string
[] args)
{
Singleton s1
=
Singleton.Instance;
Singleton s2
=
Singleton.Instance;
if
(
object
.ReferenceEquals(s1, s2))
Console.WriteLine(
"
两个对象是相同的实例。
"
);
else
Console.WriteLine(
"
两个对象非相同的实例。
"
);
}
}
}
查看全文
相关阅读:
读书笔记——吴军《态度》
JZYZOJ1237 教授的测试 dfs
NOI1999 JZYZOJ1289 棋盘分割 dp 方差的数学结论
[JZYZOJ 1288][洛谷 1005] NOIP2007 矩阵取数 dp 高精度
POJ 3904 JZYZOJ 1202 Sky Code 莫比乌斯反演 组合数
POJ2157 Check the difficulty of problems 概率DP
HDU3853 LOOPS 期望DP 简单
Codeforces 148D. Bag of mice 概率dp
POJ3071 Football 概率DP 简单
HDU4405 Aeroplane chess 飞行棋 期望dp 简单
原文地址:https://www.cnblogs.com/flaaash/p/1020841.html
最新文章
SOC-training image镜像内核文件(DE1-soc软件实验”hello_word")
博客转发小工具2
博客转发小工具1
SpringBoot学习(二)
SpringBoot学习(五)
SpringBoot学习(四)
SpringBoot学习(三)
SpringBoot学习(七)
SpringBoot学习(六)
ASP.NET MVC5(三):表单和HTML辅助方法
热门文章
ASP.NET MVC5(二):控制器、视图与模型
Natas3 Writeup(爬虫协议robots.txt)
Natas2 Writeup(水平越权)
Natas1 Writeup(查看页面源码)
Natas0 Writeup(前端源码、敏感信息)
Natas0-34 Writeup
读书笔记——李笑来《 韭菜的自我修养》
读书笔记——吴军《数学之美》之信息指纹及其应用
mysql & Tomcat使用问题记录
XSS构造剖析
Copyright © 2011-2022 走看看