I’m currently completing a project in PHP, but the general principles of OO still apply.
I have a parent class called Node, which is abstract – i.e. it cannot be instantiated. There are many classes that extend Node, and are instantiable. Some of these include Event, Person, and Project.
The issue I’m having is that I often need to instantiate a Node without knowing which child class it will be. All Node and node-sub-classes always takes the same type of object (a row from a database) as an argument to the constructor. To get around the problem of not knowing what type of implementing class I need, I created a simple static class that will return the correct sub-class of node. An example of this code is as follows:
<?php
class NodeClassRegistry{
public static function init_class($node) {
switch ($node->type) {
case 'person':
return new Person($node);
case 'event':
return new Event($node);
}
}
}
?>
This seems like really bad design to me – it’s kind of a factory pattern, but it seems really tied to global state. Is there a design pattern that would be appropriate for this situation?
What you do is a special type of the Factory Method design pattern The C++ example for this subtype in the GoF book is the following: