why we are going for singleton pattern:
if you need to ensure that a class only has one instance and provides a global point of access to it from a well-known access point.
simple example code:
namespace DesignPatterns { public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton() { }
public static Singleton Instance { get { return instance; } } } }
// code to access the Singleton. using System.Diagnostics; using DesignPatterns; Trace.WriteLine(Singleton.Instance.ToString());
Explanation
i) Singleton's constructor is set to private. This ensures that no other code in your application will be able to create an instance of this class. This enforces the requirement that there ever only be one instance of this class.
2) instance member variable is defined of the same type as the class. This instance member is used to hold the only instance of our class. The variable is static so that it is defined only once. In the .NET Framework, static variables are defined at a point before their first use (that's the actual description of their implementation). Also, the instance variable is readonly so that it cannot be modified - not even by any code that you may write in the class's implementation.
3)a public Instance property is defined with only a get method that way callers can access the instance of this class without ever being able to change it. The property is also static to provide global access from anywhere in your program. This ensures the global point of access requirement for the Singleton.
4) to test the code, you can run code that accesses your Singleton class. As you can see above, it's easy enough to get at the instance of your class:
Singleton.Instance;
Place a breakpoint in instance member variable definition and another one in the Instance property get code, then run the Debugger on this code. You will notice that the member variable creation is hit just before the call to the Instance property. Also, if you place multiple calls to Singleton.Instance, you will notice that the instance member variable is only the first time, all other calls just return the cached instance variable.
And, that is the only way to get an instance of a singleton class. If you try to create an instance of the Singleton class using the new operator:
Singleton NewInstance = new Singleton();
Than, you will get a compiler error stating that the class cannot be created because the constructor is inaccessible due to its protection level.
|
| Author: http://venkattechnicalblog.blogspot.com/ 09 Jun 2008 | Member Level: Diamond Points : 0 |
Really gud one.
Venkatesan Prabu . J
|
| Author: komaladevi 09 Jun 2008 | Member Level: Gold Points : 1 |
you have explined clearly but as it is code snippet it is okay but whole application i want
|