For their own shortcomings and deepen the understanding of PHP, choose to use PHP to study various design patterns.
Today I saw the introduction of design patterns, and learned the factory model, because the factory model is relatively simple, but also more commonly used. The most important role of the factory pattern is the encapsulation of object creation, simplifying the creation of object operations.
Here is a simple example:
Abstract class parents
{
Public function Show () {}
}
Class Sons extends Parents
{
Public Function Show ()
{
Echo ' I am son! ';
}
}
Class Girls extends Parents
{
Public Function Show ()
{
Echo ' I am girl! ';
}
}
Class Factory
{
Private $arrParent = Array ();
Public function Create ($parent)
{
$this->arrparent[] = new $parent ();
}
Public Function Show ()
{
foreach ($this->arrparent as $par)
{
$par->show ();
}
}
}
$factory = new Factory ();
$factory->create (' Sons ');
$factory->create (' Girls ');
$factory->show ();
?>
Factory mode should be more, the most used is to use the factory according to the conditions of the dynamic selection of the object to be created. The advantage of this is that you can add new object creation in just modifying the factory and the new class, which is a good choice for code maintenance and extension, and provides more flexibility in the application of dynamic object creation.