Sunday, May 23, 2010

First what is meant by software design pattern?

It’s a standard solution for a recurring problem. that many developers before u faced the same problem u r facing now and most of them did a similar solution to it, so it became a standard solution (pattern) to this problem.

Singletone Design Pattern. It’s a situation when u want ur class’s object to be created once and any coder want to make another object,  ur class code will check if there is an instance was created before, if so, it will references the new object to the existing one, if not, it will return a new one.

Actually this technique does this by making this object to be returned as a static object, thus to be resident(cached) in memory and any attempt to make another instance like it will be referenced to its place in memory.

How To DO?

Simply u make a protected constructor(so no one can create an instance directly by a new keyword).then define a private static null field of the same type of ur containing class. then code a static method returns the same type of ur containing class (thus, first time the method called an object is created and the method will check is the private static field is null ,if so ,it will create a new one as it can access the constructor as it’s a member of the class) and will assign the new instance to that private static field and return it.

Next time any code attempting to create a new instance by calling the static method it will check the nullability of the static field and will find it != null. So it will return it, not creating a new one.

Code Snippet
  1. class SingleTone
  2. {
  3. static SingleTone _instance = null;
  4. protected SingleTone()
  5. {
  6. }
  7. public static SingleTone NewInstance()
  8. {
  9. if (_instance == null)
  10. {
  11. _instance = new SingleTone();
  12. }
  13. return _instance;
  14. }
  15. }
  16. static void Main(string[] args)
  17. {
  18. SingleTone singleTone1 = SingleTone.NewInstance();
  19. //first call create a new object
  20. SingleTone singleTone2 = SingleTone.NewInstance();
  21. //further calls will return the first created object
  22. }


C# fast-food by:
Eng.Waleed abou-zaid
Senior Software Developer
Harf Information Technology
MCSD.Net,MCAD.Net,MCP,A+,N+ certified