Friday, September 14, 2007

Singleton Pattern

The singleton pattern in C# is very simple to implement and very useful. This pattern ensures that there is only one instance of its self providing a global point of access. There are different ways of doing this but I like to use the example below  because it is thread safe and clean.

public class User
{ private int _userId = 1; private static User _instance = new User(); static User() { } private User() { } public int UserId { get { return _userId ; } set { _userId = value; } } public static User Instance { get { return _instance; } }
}
Here is a quick test I wrote in NUnit that shows how it is used and comfirms there is only one instance.
[Test]
 public void TestSingleton()
 {
     User sngle1 = User.Instance;
     sngle1.UserId = 1;
     User sngle2 = User.Instance;
     sngle2.UserId = 2;
     Assert.AreEqual(sngle2.UserId, sngle1.UserId);
 }

More Info:

Everything you need to know about C# singleton.

More Patterns

#     Comments [3]  
kick it on DotNetKicks.com