日期:2008-12-21 浏览次数:20533 次
上次我们简单介绍了静态成员,今天再延伸一下,看看设计模式中的单件模式(Singleton),我先照搬一些理论
Singleton-对象创建型模式
class Singleton
{
public static Singleton Instance() = new Singleton();
}
Class Singleton
Public Shared Instance As Singleton = New Singleton
End Class
| |||
| C# | VB | ||
可是实际中如何运用呢?据个例子,我们现在要做一个游戏,而游戏中需要加载一些Sprite,这些Sprite来自于一些bmp资源,为了提升性能并使程序中只有一个实例,这时我们考虑使用Singleton模式
class Sprites
{
/// <summary>
/// Public field giving access the the instance of the Sprites class.
/// </summary>
public static readonly Sprites Instance = new Sprites();
public Bitmap[] Tiles;
/// <summary>
/// Private variable indicating if the sprites are loaded or not.
/// </summary>
private bool doneLoading;
/// <summary>
/// Method loading the sprites from the assembly resource files
/// into the public bitmap array. To be sure the sprites are only loaded
/// once a private bool is set to true/false indicating if the sprites
/// have been loaded or not.
/// </summary>
public void LoadSprites()
{
if(!doneLoading)
{
Assembly asm = Assembly.GetExecutingAssembly();
Bitmap tiles = new Bitmap(asm.GetManifestResourceStream("game.Data.Sprites.Tiles.bmp"));
//Parse the sprite strips into bitmap arrays.
Tiles = ParseSpriteStrip(tiles);
tiles.Dispose();
doneLoading = true;
}
}
/// <summary>
/// The constructor is made private to ensure that
/// the class cannot be explicitly created
/// </summary>
private Sprites()
{
}
}
Class Sprites
'***********************************
' Public field giving access the the instance of the Sprites class.
'***********************************
Public Shared ReadOnly Instance As Sprites = New Sprites
Public Tiles As Bitmap()
'***********************************
' Private variable indicating if the sprites are loaded or not.
'***********************************
Private doneLoading As Boolean
'***********************************
' Method loading the sprites from the assembly resource files
' into the public bitmap array. To be sure the sprites are only loaded
' once a private bool is set to true/false indicating if the sprites
' have been loaded or not.
'***********************************
Public Sub LoadSprites()
If Not Me.doneLoading Then
Dim asm As Assembly = Assembly.GetExecutingAssembly
Dim tiles As New Bitmap(asm.GetManifestResourceStream("game.Data.Sprites.Tiles.bmp"))
'Parse the sprite strips into bitmap arrays.
Tiles = ParseSpriteStrip(tiles)
tiles.Dispose
Me.doneLoading = True
End If
End Sub
'***********************************
|