Thursday 26 July 2012

Singleton Method


What is Singleton

Singleton ensures that  a class only has one instance, and provides a global point of access to it.This is the simplest of all patterns.


Explanation

Singleton pattern creates a class which can have a single object throughout the application, so that whenever any other object tries to access the object of the class, it will access the same object always.
Now, here there are two things:

  1. Class is static and you should not instantiate the class at any other class.
  2. You need the instance of this class.
If we think of the basic OOPS concept. If we want the class not to be accessed , we should declare it as private. But if I say it as private how do I access it outside the class.

So, to solve this :
  • make the constructor private and sealed
  • add a public static property to access the object of this class

Example:


Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves, for example  a single PC there is one and only one window manager.

Its used in Logger class,Configuration class,accessing an external resource in shared mode.(File System.)

Also, it can be implemented through when using Factory pattern and Abstract pattern.




No comments:

Post a Comment