会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
进步太慢就是退步
博客园
首页
新随笔
联系
订阅
管理
代码:单件模式(Singleton Pattern)
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
DesignPatterns.Singletons
{
//
一个类有且仅有一个实例,并且提供了一个全局的访问点
/**/
///
<summary>
///
简单
///
</summary>
public
sealed
class
Singleton01
{
static
Singleton01 instance
=
null
;
private
Singleton01()
{
}
static
Singleton01 Instance
{
get
{
if
(instance
==
null
)
{
instance
=
new
Singleton01();
}
return
instance;
}
}
}
/**/
///
<summary>
///
线程安全,单锁:每次都锁,性能欠佳
///
</summary>
public
sealed
class
Singleton02
{
static
Singleton02 instance
=
null
;
static
readonly
object
olock
=
new
object
();
private
Singleton02()
{
}
static
Singleton02 Instance
{
get
{
lock
(olock)
{
if
(instance
==
null
)
{
instance
=
new
Singleton02();
}
return
instance;
}
}
}
}
/**/
///
<summary>
///
线程安全,双锁:为空时锁
///
</summary>
public
sealed
class
Singleton03
{
static
Singleton03 instance
=
null
;
static
readonly
object
olock
=
new
object
();
private
Singleton03()
{
}
static
Singleton03 Instance
{
get
{
if
(instance
==
null
)
{
lock
(olock)
{
if
(instance
==
null
)
//
解决了线程并发问题,同时避免在每个 Instance 属性方法的调用中都出现独占锁定
{
instance
=
new
Singleton03();
}
}
}
return
instance;
}
}
}
/**/
///
<summary>
///
静态初始化,实例化机制的控制权较少
///
</summary>
public
sealed
class
Singleton04
{
static
readonly
Singleton04 instance
=
new
Singleton04();
private
Singleton04()
{
}
static
Singleton04()
{
}
static
Singleton04 Instance
{
get
{
return
instance;
}
}
}
}
posted @
2009-06-04 14:08
RobertFang
阅读(
173
) 评论(
0
)
收藏
举报
刷新页面
返回顶部
公告