Design Patterns Reference: Singleton

“The singleton Design Pattern is used to restrict the number of times a specific object can be created to a single time by providing access to a shared instance of itself.”

 

“The constructor of the object should be a protected method. This will not allow anything but the class itself to create an instance of it. Then it can make a public method to actually create, store, and provide that instance.”

 

Most common use: database connection

 

More interesting possible use, food for thought: configuration option management…

 

class InventoryConnection
{
protected static $_instance = NULL;
protected $_handle = NULL;
public static function getInstance()
{
if(!self::$_instance instanceof self){
self::$_instance = new self;
}
return self::$_instance;
}

 

protected function __construct()
{
$this->_handle = mysql_connect(‘localhost’,’user’,’pass’);
mysql_select_db(‘CD’, $this->_handle);
}

 

public function updateQuantity($band, $title, $number)
{
$query = “update CDS set amount = amount+” . intval($number);
$query .= ” where band=‘ ” . mysql_real_escape_string($band) . ” ‘ “;
$query .= ” and title=‘ ” . mysql_real_escape_string($title) . ” ‘ “;
mysql_query($query, $this->_handle);
}
}

 

class CD
{
protected $_title = ‘ ‘;
protected $_band = ‘ ‘;
public function __construct($title, $band)
{
$this->_title = $title;
$this->_band = $band;
}

 

public function buy()
{
$inventory = InventoryConnection::getInstance();
$inventory->updateQuantity($this->_band, $this->_title, -1);
}
}

 

$boughtCDs = array();
$boughtCDs[] = array(‘band’=>’Never Again’, ‘Waste of a Rib’);
$boughtCDs[] = array(‘band’=>’Therapee’, ‘Long Road’);

 

foreach($boughtCDs as $boughtCD){
$cd = new CD($boughtCD[‘title’], $boughtCD[‘band’]);
$cd->buy();

 

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

 

 

Leave a Reply

You must be logged in to post a comment.