Friday, December 12, 2008

Understanding to use Singleton Pattern

Singleton - for all those of you who have been single in life can understand this as it would seem the story of your life.

Singleton means only one instance of the class we are referring, such as in a website application DatabaseHandler, Logger, ErrorHandler are a few class whose names do tell there functionality by itself.

But to understand the keypoint in this is all these classes there is one thing in common mostly which is that they all interact with a resource that is common in the sense that when,

I am making a connection to the database and executing some queries I would be using the same resource.

I am logging some user action somewhere in storage i would be using the same path

If I am recording errors in my application I would want a centralized control, for all the above scenarios Singleton fits the bill, here is how you use it in your classes.

create a static function by convention named getInstance() inside the class and make the contructor private.

Let me give you some examples in PHP,

class DatabaseConnection
{
private static $_instance = null;

private function __construct()
{
self::$instance = mysql_connect('host', 'username', 'password');
}

public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new self();
}

return self::$instance;
}

public function __clone()
{
// throw exception and log it in your website centralized database
}
}

No comments:

Post a Comment