单件模式,单件意味着唯一,我们创建的类的实例是唯一的。唯一的处理打印机,消息队列,注册表等等.......
UML图:
单件模式看来简单,其实不然。包括什么双重加锁(多线程要求),延迟实例化等等,具体在TerryLee的blog上有详细的描述,本文不再罗嗦。
单件模式没有公开的构造函数,要实现对象的实例化只能依靠静态的
GetInstance方法。在
GetInstance方法中判断对象是否存在,存在则返回该对象,不存在就实例化一个对象返回。
Dota中时间是唯一的,以下的例子是对白天黑夜的控制,也就是我们的夜魔技能。
测试代码:
DotaPatternLibrary.Singleton.GameTime gtObj = DotaPatternLibrary.Singleton.GameTime.GetInstance();
LandpyForm.Form.OutputResult("Game时间类型:" + gtObj.TimeType);
Thread balanarGamerThread = new Thread(new ThreadStart(BalanarDarkTime));
Thread akashaGamerThread = new Thread(new ThreadStart(AkashaGetTimeType));
balanarGamerThread.Start();
akashaGamerThread.Start();
///
<summary>
///
暗夜魔王放大
///
</summary>
public
void
BalanarDarkTime()
{
LandpyForm.Form.OutputResult(
"
夜魔(Balanar)大招
"
);
DotaPatternLibrary.Singleton.GameTime gtObj
=
DotaPatternLibrary.Singleton.GameTime.GetInstance();
gtObj.TimeType
=
DotaPatternLibrary.Singleton.TimeTypeValue.Evening;
for
(
int
i
=
1
; i
<
5
; i
++
)
{
Thread.Sleep(
2000
);
LandpyForm.Form.OutputResult(
"
时间过去
"
+
i
*
2
+
"
秒
"
);
}
LandpyForm.Form.OutputResult(
"
夜魔(Balanar)大招时间到
"
);
DotaPatternLibrary.Singleton.GameTime gtObjNew
=
DotaPatternLibrary.Singleton.GameTime.GetInstance();
gtObjNew.TimeType
=
DotaPatternLibrary.Singleton.TimeTypeValue.DayTime;
}
///
<summary>
///
痛苦女王获得时间类型
///
</summary>
public
void
AkashaGetTimeType()
{
for
(
int
i
=
1
; i
<
4
; i
++
)
{
Thread.Sleep(
2000
);
DotaPatternLibrary.Singleton.GameTime gtObj
=
DotaPatternLibrary.Singleton.GameTime.GetInstance();
LandpyForm.Form.OutputResult(
"
痛苦女王(Akasha)获得时间:
"
+
gtObj.TimeType);
Thread.Sleep(
3000
);
}
}
完整代码:
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
DotaPatternLibrary.Attribute;
namespace
DotaPatternLibrary.Singleton
{
class
Singleton
{
public
static
object
lockObj
=
new
object
();
private
static
Singleton singleton;
private
Singleton()
{
}
public
static
Singleton GetInstance()
{
lock
(lockObj)
{
if
(singleton
==
null
)
{
singleton
=
new
Singleton();
}
}
return
singleton;
}
}
public
class
TimeTypeValue
{
public
const
string
DayTime
=
"
DayTime(白天)
"
;
public
const
string
Evening
=
"
Evening(夜晚)
"
;
}
public
class
GameTime
{
private
static
object
lockObj
=
new
object
();
private
static
GameTime gameTime;
private
string
_timeType;
public
string
TimeType
{
get
{
return
_timeType; }
set
{ _timeType
=
value; }
}
private
GameTime()
{
this
._timeType
=
TimeTypeValue.DayTime;
}
public
static
GameTime GetInstance()
{
lock
(lockObj)
{
if
(gameTime
==
null
)
{
gameTime
=
new
GameTime();
}
}
return
gameTime;
}
}
}