php-Factory mode

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.