Definitely, one of the simplest way to implement the Singleton pattern inside the example form element factory class that you saw before is to add a static method, usually called “getInstance()” (or something similar) that takes care of returning to client code only one instance of it. Period. To demonstrate in detail how this static method can be coded in a few simple steps, below I reintroduced the definition of the factory class, which this time includes the pertinent “getInstance()” method. Take a look at it, please: class FormElementFactory { private static $instance = NULL;
// get Singleton instance of form element factory class public static function getInstance() { if (self::$instance === NULL) { self::$instance = new FormElementFactory; } return self::$instance; } public function factory($formElement, $attributes = array()) { if ($formElement === 'textbox' or $formElement === 'textarea') { return new $formElement($attributes); } } } That wasn’t rocket science, wasn’t it? As you can see, now the “FormElementFactory” class implements the Singleton pattern through its “getInstance()” method, which internally uses a $instance static property, to return only a single instance of the class. While I’m still far from defining a truly effective factory method, it’s fair to say that the incorporation of the previous “getInstance()” Singleton is a considerable improvement for avoiding issues related to multiple instances. Well, at this stage I’m pretty sure that you understand the purpose of coding the static “getInstance()” method. However, the missing part here is the lack of an example that shows how to use this method in conjunction with the already familiar “factory()” to create some form element objects. In the last segment of this tutorial I’m going to code that example, so you can see in action the improved version of the sample “FormElementFactory” class. Please click on the link that appears below and read the final section.
blog comments powered by Disqus |
|
|
|
|
|
|
|