NAME : SINGLETON PATTERN
Singleton pattern is a gang of four pattern. This is a creational pattern as it is used to control class instantiation.
CONTEXT : To ensure the combination of two essential properties
(i) only one instance of an object is created
(ii) provide global point of access to a limited resource.
PROBLEM : creating a global variable leads to multiple access points, copied and the risk that the duplication may become out of step with the original one.
Global variable could be used, but although it does make the object accessible,it does not keep you instantiating multiple objects.
SOLUTION : A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instances can be created by interception requests to create new objects and it can provide a way to access the instance and then query the class for the instance.
Because access is controlled by a class ,the class method can include additional logic needed to handle these queries.
The singleton pattern serves as a replacement for global variables and global functions that act on them. It preserves the restriction that there can be only one instance of class. All further references to objects of the singleton class refers to the same underlying instance. Singleton is often used to hold the state of a program, particular in rich client application.
Advantage : because it is designed to work with a single specific class, it can also take the relavant class file is loaded when necessary.
Examples: legacy data file that only supports a single reader at a time , objects needed for logging, database access, communication etc...
No comments:
Post a Comment