C H A P T E R 9
■ ■ ■
Generating Objects
Creating objects is a messy business. So many object-oriented designs deal with nice, clean abstract
classes, taking advantage of the impressive flexibility afforded by polymorphism (the switching of
concrete implementations at runtime). To achieve this flexibility though, I must devise strategies for
object generation. This is the topic I will look at here.
This chapter will cover
- The Singleton pattern: A special class that generates one and only one object
instance - The Factory Method pattern: Building an inheritance hierarchy of creator classes
- The Abstract Factory pattern: Grouping the creation of functionally related
products - The Prototype pattern: Using clone to generate objects
Problems and Solutions in Generating Objects
Object creation can be a weak point in object-oriented design. In the previous chapter, you saw the
principle “Code to an interface, not to an implementation.” To this end, you are encouraged to work
with abstract supertypes in your classes. This makes code more flexible, allowing you to use objects
instantiated from different concrete subclasses at runtime. This has the side effect that object
instantiation is deferred.
Here’s a class that accepts a name string and instantiates a particular object:
abstract class Employee {
protected $name;
function __construct( $name ) {
$this->name = $name;
}
abstract function fire();
}
class Minion extends Employee {
function fire() {
print "{$this->name}: I'll clear my desk\n";
}
}