Datasheet
DESIGN PATTERNS IN WEB FRAMEWORKS
x
19
Customer_2 wants to rent the car. Again.
Customer_2 says: I drive Dodge Magnum really fast!
The Singleton pattern is used often in other design patterns such as Prototype, State, Abstract
Factory, or Facade. Apart from that, it can be used in all classes where you need a single
instance with global access, but there is no way to assign it to another object, and perhaps you
can also benefi t from initialization on the fi rst use. Be wary, though, because it is easy to over-
use Singletons, and they may be dangerous, just like global variables. Another problem with
Singletons is that they carry their state throughout the execution of the program, which seriously
harms unit testing. Some experts even argue that Singleton is a bad idea and it generally should
be avoided.
Frameworks use Singletons for various reasons. One of them is storing user data for security pur-
poses. You want to have a single instance of a user that holds authentication data and make sure
that no second instance can be created. This approach is represented, for example, by the
sfGuard
class of Symfony.
Prototype
The Prototype pattern is useful when you need the fl exibility of parameterized object creation and
when you want to avoid using the
new operator. Object creation is done here by creating a parent
class with an abstract
clone() method and a few subclasses implementing clone(). Each of these
subclasses comes with one instantiated Prototype object, which clones itself when you call for a new
instance. This results in easiness and fl exibility of object creation — you don’t have to hard-wire the
concrete subclass name in your code. Instead you can pass the name of the class as a string or refer-
ence to the appropriate Prototype.
This pattern also greatly supports deep copying of objects. Instead of cloning the Prototype, you
can clone an existing object, receiving an exact copy as the result. You can even copy objects from
a container with mixed objects of various subclasses. The only requirement is that they implement
the
clone() interface. Copying objects this way is much faster than creating objects with new and
assigning values. A general diagram of this pattern is shown in Figure 1-20.
+CarPrototype order(String model)
CarDealer
+clone()
CarPrototype
+clone()
DodgePrototype
+clone()
SubaruPrototype
FIGURE 120: Prototype pattern structure
PHP has another magic function: __clone()does most of the work for you. All you have to do
in the following example is to create an abstract
CarPrototype class and subclasses for different
producers. The
__clone() function is declared abstract, so subclass methods are used by default
when this method is called.
c01.indd 19c01.indd 19 1/24/2011 5:45:19 PM1/24/2011 5:45:19 PM