Understanding the Factory Pattern of PHP

Source: Internet
Author: User

The factory class is a class specifically used to create other objects. The factory class is very important in the practice of polymorphism programming. It allows Dynamic Replacement of classes and Configuration modification, making the application more flexible. Mastering the factory model is essential for Web development.

The factory mode is usually used to return different classes similar to interfaces. A common usage of the factory is to create a multi-state provider.

Generally, the factory mode has a key structure, that is, the static method named factory. This static method can accept any number of parameters and must return an object.

Program List: Basic factory class
<? Phpclass Fruit {// object returned from the factory Class} Class FruitFactory {public static function factory () {// return a new instance of the object return new Fruit ();}} // call the factory $ instance = FruitFactory: factory ();?>
Program List: use factory-class production objects
    <?phpclass Example{    // The parameterized factory method    public static function factory($type)    {        if (include_once 'Drivers/' . $type . '.php') {            $classname = 'Driver_' . $type;            return new $classname;        } else {            throw new Exception('Driver not found');        }    }}// Load a MySQL Driver$mysql = Example::factory('MySQL');// Load an SQLite Driver$sqlite = Example::factory('SQLite');?>
Program List: a complete factory class

The following program defines a general factory class, which produces null objects that can save all your operations. You can get an instance, and these operations are all in that instance.

<?php        /**     * Generic Factory class     *     * This Magic Factory will remember all operations you perform on it,     * and apply them to the object it instantiates.     *     */    class FruitFactory {        private $history, $class, $constructor_args;                /**         * Create a factory of given class. Accepts extra arguments to be passed to         * class constructor.         */        function __construct( $class ) {            $args = func_get_args();            $this->class = $class;            $this->constructor_args = array_slice( $args, 1 );        }                function __call( $method, $args ) {            $this->history[] = array(                'action'    => 'call',                'method'    => $method,                'args'   => $args            );        }                function __set( $property, $value ) {            $this->history[] = array(                'action'    => 'set',                'property'    => $property,                'value'        => $value            );        }                /**         * Creates an instance and performs all operations that were done on this MagicFactory         */        function instance() {            # use Reflection to create a new instance, using the $args             $reflection_object = new ReflectionClass( $this->class );             $object = $reflection_object->newInstanceArgs( $this->constructor_args );                         # Alternative method that doesn't use ReflectionClass, but doesn't support variable            # number of constructor parameters.            //$object = new $this->class();                        # Repeat all remembered operations, apply to new object.            foreach( $this->history as $item ) {                if( $item['action'] == 'call' ) {                    call_user_func_array( array( $object, $item['method'] ), $item['args'] );                }                if( $item['action'] == 'set' ) {                    $object->{$item['property']} = $item['value'];                }            }                        # Done            return $object;        }    }        class Fruit {        private $name, $color;        public $price;                function __construct( $name, $color ) {            $this->name = $name;            $this->color = $color;        }                function setName( $name ) {            $this->name = $name;        }                function introduce() {            print "Hello, this is an {$this->name} {$this->sirname}, its price is {$this->price} RMB.";        }    }        # Setup a factory    $fruit_factory = new FruitFactory('Fruit', 'Apple', 'Gonn');    $fruit_factory->setName('Apple');    $fruit_factory->price = 2;        # Get an instance    $apple = $fruit_factory->instance();    $apple->introduce();?>

Program running result:

Hello, this is an Apple , its price is 2 RMB.

The factory mode mainly provides a transitional interface for creating objects, so that the specific process of creating objects is blocked and isolated to improve flexibility.

The factory model can be divided into three types:

  • Simple Factory)
  • Factory Method)
  • Abstract Factory)

These three models are gradually abstracted from top to bottom and more general.

The simple factory mode is also called the static factory method mode. After renaming, we can see that this mode must be very simple. Its purpose is to define an interface for creating objects. The factory method mode removes the static attribute of the factory method in the simple factory mode so that it can be inherited by the quilt class. In this way, the pressure on the factory method in the simple factory mode can be shared by different factory subclass in the factory method mode.

The factory method mode seems to have perfectly packaged the object creation, so that the client program only processes the interfaces provided by the abstract Product role. So do we have to spread code across factories? Not required. You may consider using the factory method mode in the following situations:

  • When the customer program does not need to know the creation process of the object to be used.
  • The objects used by the customer program may change, or they do not know which specific object to use.

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.