Why Singleton?
What is Singleton Pattern
The Sample Code
Here’s a singleton recommended check list:
If your requirement confirms all these points, then it’s a good candidate to use the singleton pattern.
Sometimes we want just a single instance of a class to exist in the system. For example, we want just one database manager instance. We need to have that one instance easily accessible and we want to ensure that additional instances of the class can not be created.
What is Singleton Pattern
The singleton is a useful design pattern that is used to restrict instantiation of a class to one object. It ensures a class has only one instance and provide a global point of access to it. In the singleton pattern at any given point only a single instance of the Singleton Class is active. All instantiation of the Singleton Class references the same instance of the Class. The pattern also provides a global point of access to the sole instance of the class.
The Sample Code
Class SingletonBenefits of Singleton Pattern:
{
//Class Members
private static $instance;
//The Constructor
protected function Singleton() {}
//Static method for creating the single instance of the Constructor
public static function getInstance()
{
// create a new instance if not already done
if( $instance == null )
$instance = new Singleton();
// return the instance of the Singleton Class
return $instance;
}
}
- Instance control: It ensures that all objects access the single instance, by preventing other objects from instantiating their own copies of the Singleton object.
- Flexibility: The class has the flexibility to change the instantiation process. Because it controls the instantiation.
- As Global variables: Singletons are often preferred to global variables because -
- They don't pollute the global namespace with unnecessary variables.
- They allow lazy allocation and initialization, where global variables in many languages will always consume resources.
- It is usually not recommended to use global objects, since it is hard to test them and the developer has to make assumptions regarding the application and how they will be used.
- Using the singleton pattern makes the classes tightly coupled instead of loosely coupled, meaning that you can only test a few classes together rather than each of the classes at a time, as you should.
Here’s a singleton recommended check list:
- Singleton should be used in cases where only one object is needed to coordinate actions and/or events across the application.
- The application will always use the object in the same way.
- It doesn’t really matter to the client what’s going on in the rest of the application, meaning that the singleton object is independent.
If your requirement confirms all these points, then it’s a good candidate to use the singleton pattern.
No comments:
Post a Comment