home screen

Search



Number Of Result : 0

Result :


Friday, November 28, 2008

Singleton Pattern

- Role
The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object. Moreover, the object should not be created until it is actually needed. In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.





- Example 5-4. Singleton pattern theory code

1 public sealed class Singleton {
2 // Private Constructor
3 Singleton( ) { }
4
5 // Private object instantiated with private constructor
6 static readonly Singleton instance = new Singleton( );
7
8 // Public static property to get the object
9 public static Singleton UniqueInstance {
10 get { return instance;}
11 }
12 }



- Use it.

Singleton s1 = Singleton.UniqueInstance;



- Singleton pattern generic code

1 using System;
2
3 // Singleton Pattern Judith Bishop Nov 2007
4 // Generic version
5
6 public class Singleton where T : class, new( ){
7 Singleton( ) { }
8
9 class SingletonCreator {
10 static SingletonCreator ( ) {}
11 // Private object instantiated with private constructor
12 internal static readonly T instance = new T( );
13 }
14
15 public static T UniqueInstance {
16 get {return SingletonCreator.instance;}
17 }
18 }
19
20 class Test1 {}
21 class Test2 {}
22
23 class Client {
24
25 static void Main ( ) {
26 Test1 t1a = Singleton.UniqueInstance;
27 Test1 t1b = Singleton.UniqueInstance;
28 Test2 t2 = Singleton.UniqueInstance;
29
30 if (t1a == t1b) {
31 Console.WriteLine("Objects are the same instance");
32 }
33 }
34 }


Reference : C# 3.0 Design Patterns Ebook.

No comments: