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(
"
两个对象非相同的实例。
"
);
}
}
}
查看全文
相关阅读:
cocos2d-x学习笔记(贪吃蛇代码)
jQuery中animate的height的自适应
[Docker02]Docker_registry
[Docker03] Deploy LNMP on Docker
Python OS Module
前端设计框架
Ansible权威指南-读书笔记
python+selenium之悠悠博客学习笔记
jenkins入门
sed
原文地址:https://www.cnblogs.com/flaaash/p/1020841.html
最新文章
linux配置java环境变量(详细)
Nutch介绍及使用
Open edX 学习、开发、运维相关链接整理
在linux系统中安装virtualbox增强功能(增强包)的详细步骤
CentOS下添加用户并且让用户获得root权限
将TXT文件 导入 sqlserver数据库
Tomcat 一端口多项目,多端口多项目 server.xml
SpringBoot_Mybatis_Maven_BootStrap
SpringMVC_JDBC
SpringMVC
热门文章
Servlet_Struts2
NewEmployeesLearnNotes——新人程序员学习计划V1.1
CreateProjectFormat——初始项目目录格式
egret中场景跳转的动画
typeScript类里面的属性声明
cocos2d-html5 碰撞检测的几种方法
手把手教你如何使用Cocos2d Console 进行html5项目发布
【Cocos2d-html5】运动中速度效果
cocos2d-x js 中创建node的方法
cocos2d-x学习笔记(斗地主代码)
Copyright © 2011-2022 走看看