A Practical Example of Static Costructor in C# .NET (Singletons)
Singletons provide an excellent example of private and static constructors. A singleton is an object that appears once in the problem domain. Singletons are limited to one instance, but that instance is required. This requirement is enforced in the implementation of the singleton.
The singleton presented in this chapter has two constructors. The private constructor means that an instance cannot be created outside the class. That would require calling the constructor publicly. However, an instance can be created inside the class. The single instance of the class is exposed as a static member, which is initialized in the static constructor. The instance members of the class are accessible through the static instance. Because the static constructor is called automatically, one instance—the singleton—always exists.
A chess game is played with a single board—no more or less. This is the singleton for a chess board:
using System; namespace Examples.Singleton {
public class Chessboard
{
public static Chessboard board=null;
public string player1;
public string player2;
public string start
private Chessboard() {}
static Chessboard()
{
board=new Chessboard();
board.start=DateTime.Now.ToShortTimeString();
}
}
public class Game
{
public static void Main()
{
Chessboard game=Chessboard.board;
game.player1="Sally";
game.player2="Bob";
Console.WriteLine("{0} played {1} at {2}", game.player1, game.player2, game.start);
}
}
}
In Main, game is an alias for the ChessBoard.board singleton. The local variable is not another instance of Chessboard. The alias is simply a convenience. I preferred game.player1 to Chess-Board.board.player1.
-
Archives
- February 2009 (1)
- November 2008 (6)
- October 2008 (4)
- September 2008 (13)
- August 2008 (11)
- July 2008 (29)
- June 2008 (19)
- May 2008 (8)
-
Categories
-
RSS
Entries RSS
Comments RSS

