Sunday 26 June 2016

Singleton design pattern

As the name suggests this pattern is related to a notion like " only one of something ".
More specifically , when you want only one instance of a class in your program.
A very common example where this type of design pattern can be applied is when you are doing database connections.
Suppose , if you writing your database connection related code inside a function of a class called DatabaseConn . Now , everytime you create an object of that class and call that function , you are getting a "new"  database connection , which ofcouse is not necessary and is a overhead to the database server. To avoid such problems , you can apply singleton pattern, and ensure that there is only one instance of that class is generated.
The following is an example ( in php ):

//Class to make db connection
Class DbConnect {
//Static member variable to hold the connection object
private static $conn = NULL;
private static $instance = NULL;
private function __construct() {
// Create connection
self::$conn = new mysqli("hostname", "username", "password", "dbname");
// Check connection
if (self::$conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
}
public static function connect() {
if (self::$instance === NULL) {
self::$instance = new DbConnect();
return self::$instance;
} else {
return self::$instance;
}
}
}
$myDbConn = DbConnect::connect();
$myDbConn2 = DbConnect::connect(); //If you var dump these two objects , you will find that they are same instances.
var_dump($myDbConn);
var_dump($myDbConn2);

No comments:

Post a Comment