All Pages All Books|
|
|||
|
76 The Singleton Pattern
The Solution
Of course, a global variable is an obvious solution, but it’s also a Pandora’s Box (The saying, “Good judgment comes from experience, but experience usually comes from poor judgment” comes to mind.) Any portion of your code can modify a global variable, causing endless aggravation debug-ging any number of serendipitous problems. In other words, the state of a global variable is always questionable. (A good description of the global variable dilemma can be found at http://c2.com/cgi/wiki?GlobalVariablesAreBad.)
When you need an exclusive instance of a particular class, use the aptly-named Singleton pat-tern. A class based on the Singleton pattern properly instantiates and initializes one instance of the class and provides access to the exact same object every time, typically through a static method named getInstance().
Getting the exact same instance every time is critical and worthy of a test:
|
|||
|
|
|||
|
// PHP4
function TestGetInstance() { $this->assertIsA(
$obj1 =& DbConn::getInstance(),
‘DbConn’,
‘The returned object is an instance of DbConn’); $this->assertReference(
$obj1,
$obj2 =& DbConn::getInstance(),
‘Two calls to getInstance() return the same object’); }
|
|||
|
|
|||
|
®
|
assertReference
assertReference() ensures that the two passed parameters are references to the same PHP variable.
In PHP4, this asserts the two tested parameters are in fact the same object. assertReference() may be deprecated as SimpleTest is migrated to PHP 5.
This test method makes two assertions: that the value returned from calling the static DbConn::getInstance() method is an instance of the DbConn class and that a second call to getInstance() returns the same reference, which implies it’s the very same object.
Besides asserting the expected behavior of the code, the test also demonstrates the proper (PHP4) usage of getInstance(): $local_conn_var =& DbConn::getInstance();. The local variable is assigned the result of the static method call by reference (=&).
There’s one other test to write, at least for now: verify that instantiating a Singleton class
|
||
|
|
|||
All Pages All Books