Examples of simple factory patterns in PHP design pattern programming, examples explaining design patterns _php Tutorials

Source: Internet
Author: User
Tags learn php

Examples of simple factory patterns in PHP design pattern programming, examples explaining design patterns


The Simple Factory mode is the creation mode of the class, also called the Static Factory method (Factory) mode. The simple factory model is determined by a factory object to create an instance of that product class.

1. Several forms of the factory model
The factory model is dedicated to instantiating a large number of classes with common interfaces. Factory mode can dynamically decide which class to instantiate, without knowing in advance which class to instantiate each time. The factory model has the following forms:
(1) Simple Factory mode, also known as static Factory method mode (static Factory pattern).
(2) The factory method (Factory mode), and the multiprocessing plant (polymorphic Factory) mode or virtual sub-structure model;
(3) Abstract Factory mode, also known as Toolbox (Kit or Toolkit) mode. Below is a brief class diagram of the simple factory model.

Simple Factory mode, or static factory method mode, is a special implementation of different factory method patterns. In other literature, simple factories are often discussed as a special case of common factory models.
Learning a simple factory model is a good preparation for learning the factory method model, and is also a good preparation for learning other patterns, especially singleton patterns and multiple cases.

2. Introduction of Simple Factory model

For example, there is a farm company that specializes in selling all kinds of fruit to the market. The following fruit should be described in this system:
Grape Grape
Strawberry Strawberry
Apples Apple
Fruit is very different from other plants, that is, fruit can be picked and eaten eventually. A natural way to do this is to create an interface for all kinds of fruits that can be separated from other plants in the farm. As shown in.

The fruit interface specifies the interfaces that all fruits must achieve, including the methods that any fruit must have: planting plant (), growing Grow (), and Harvesting harvest (). The class diagram for the interface fruit is shown below.

The source code for this fruit interface is shown below.
Listing 1: Source code for Interface fruit

Interface Fruit{public function grow ();p ublic function Harvest ();p ublic function Plant ();}

The Apple class is one of the fruit classes, so it implements all the methods that the fruit interface declares. In addition, because Apple is a perennial plant, so more than a treeage nature, describing the age of apple trees. Here is the source code for this Apple class.
Code Listing 2: Class Apple's source code

Class Apple implements Fruit{private $_treeage;public function grow () {echo "Apple is growing.";} Public Function Harvest () {echo "Apple has been harvested.";} Public Function Plant () {echo "Apple has been planted.";} Public Function Gettreeage () {return $this->_treeage;} Public Function Settreeage ($treeAge) {$this->_treeage = (int) $treeAge;}}

Similarly, the Grape class is one of the fruit classes and implements all the methods declared by the fruit interface. But because the grapes are both seed and seedless, there is a seedless property more than the usual fruit, as shown.

The source code for the grapes is shown below. As you can see, the Grape class also implements the fruit interface, which is a seed type of the fruit type.
Code Listing 3: source code for Class grape

Class Grape implements Fruit{private $seedless;p ublic function grow () {echo "Grape is growing.";} Public Function Harvest () {echo ' Grape has been harvested. ';} Public Function Plant () {echo ' Grape has been planted. ';} Public Function getseedless () {return $this->seedless;} Public Function setseedless ($seedless) {$this->seedless = (Boolean) $seedless;}}

The strawberry class implements the fruit interface, so it is also a subtype of the fruit type, with the source code shown below.
Code Listing 4: Source code for Class strawberry

Class Strawberry implements Fruit{public function grow () {echo "Strawberry is growing.";} Public Function Harvest () {echo ' strawberry has been harvested. ';} Public Function Plant () {echo ' strawberry has been planted. ';}}

The farm gardener is also part of the system, which naturally needs to be represented by a suitable class. This class is the Fruitgardener class, and its structure is described by the following class diagram.

The Fruitgardener class creates different fruit objects, such as Apple (apple), Grape (Grape), or strawberry (strawberry), according to the client's requirements. If you receive an illegal request, the Fruitgardener class throws an Badfruitexception exception.
The source code for the Gardener class is shown below.
Code listing 5:fruitgardener class source code

Class Fruitgardener{public static function factory ($which) {$which = Strtolower ($which); if ($which = = ' Apple ') {return new Apple ();} ElseIf ($which = = ' Strawberry ') {return new strawberry ()} elseif ($which = = ' Grape ') {return new Grape ();} else {throw NE W badfruitexception (' Bad fruit Request ');}}}

As can be seen, the Gardener class provides a static factory method. Under the client's call, this method creates the desired fruit object for the client. If the client's request is not supported by the system, the factory method throws a Badfruitexception exception. The source code for this exception class is shown below.
Code listing 6:badfruitexception class source code

Class Badfruitexception extends exception{}

When used, the client simply calls the Fruitgardener static method Factory (). Please see the following schematic
The source code of the client.
Code Listing 7: How to use the Exception class Badfruitexception

try {fruitgardener::factory (' apple '); Fruitgardener::factory (' Grape '); Fruitgardener::factory (' strawberry ');//...} catch (Badfruitexception $e) {//...}

In this way, the farm must be a good harvest!

3. Designing an "Object-oriented" calculator using the Simple factory model

/** * Object-oriented Calculator * Ideas: * 1, object-oriented basic, encapsulation, inheritance, much too * 2, the parent class * 3, various operations class *//** * base class, Operation class * Only provide basic data, do not participate in the operation */class Operation {//First   Number public $first _num = 0;   The second number is public $second _num = 0;     /** * Get results, other classes override this method * @return Double $result */Public Function GetResult () {$result = 0.00; return $result;  }}/** * Addition class */class Operationadd extends Operation {/** * overrides the parent class, implementing the addition algorithm */Public Function GetResult () {$result = 0; return $this->first_num + $this->second_num;   }}/** * Subtraction class * */class Operationsub extends Operation {/** * overrides the parent class, implementing the addition algorithm */Public Function GetResult () {$result = 0; return $this->first_num-$this->second_num;   }}/** * Multiplication class * */class Operationmul extends Operation {/** * overrides the parent class, implementing the addition algorithm */Public Function GetResult () {$result = 0; return $this->first_num * $this->second_num;     }}/** * except class * */class Operationdiv extends Operation {/** * overrides the parent class, implements the addition algorithm */Public Function GetResult () {$result = 0; if ($this->second_num = = 0) {throw new exception (' division operation the second parameter cannot be zero! ');  return 0; } return $this->first_num/$this->second_num; }}/** * Factory class */class Operationfactory {/** * Factory function * @param string $operation * @return Object */Public function Crea     Teoperation ($operation) {$oper = null;    Switch ($operation) {case ' + ': $oper = new Operationadd ();   Break    Case '-': $oper = new Operationsub ();   Break    Case ' * ': $oper = new Operationmul ();   Break    Case '/': $oper = new Operationdiv ();   Break  Default:return 0; } return $oper; }} $operation = new Operationfactory (); $oper = $operation->createoperation ('/'); $oper->first_num = ten; $oper->second_num = 20;var_dump ($oper->getresult ());

Articles you may be interested in:

    • Simple factory model of PHP design mode
    • Explanation of "Simple Factory mode" instance code in PHP
    • Example of a simple complaint page for PHP design mode
    • Example of the Observer pattern for PHP design Patterns
    • The delegate mode of PHP design mode
    • design mode of design for PHP in common use
    • PHP Design Mode Series Specification Specification mode
    • Learn PHP Design Patterns PHP Implementation Memo mode (Memento)
    • Learn PHP Design Patterns PHP Implementation viewer mode (Observer)
    • Learn PHP Design Patterns PHP Implementation Template Method pattern

http://www.bkjia.com/PHPjc/1104325.html www.bkjia.com true http://www.bkjia.com/PHPjc/1104325.html techarticle The example explains the simple Factory mode in PHP design mode programming, the example explains the design pattern Simple Factory mode is the class creation mode, also called the Static factory method Factory mode ...

  • Related Article

    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.