This article mainly introduces the simple factory mode of php design mode, also known as the static factory method mode. it is an important PHP design mode, for more information about the simple factory mode of the php design mode, also known as the static factory method mode, you can refer to this article as an important PHP design mode, for more information, see
This article introduces the simple factory mode of PHP design mode in detail in the form of examples, which is useful for PHP program design. The details are as follows:
I. concepts
Simple Factory mode [Static Factory Method] (Static Factory Method)
Is the class creation mode
Several forms of factory models:
1. Simple Factory is also called Static Factory Method)
2. Factory Method is also called Polymorphic Factory)
3. Abstract Factory is also called ToolKit)
II. graph analysis:
III. code example
The instance code can be run after testing, as follows:
TreeAge;} // set the age of the apple tree. public function setTreeAge ($ age) {$ this-> treeAge = $ age; return trie ;}} /*** define a specific product grape ** First, we need to implement the method defined by the inherited interface * and then define the unique attributes of the grape, and the method */class grape implements fruit {// indicates whether the grape has seeds private $ seedLess; public function grow () {echo "apple grow";} public function plant () {echo "apple plant";} public function harvest () {echo "apple harvest";} public function eat () {echo "apple eat ";} // seedLess function getSeedLess () {return $ this-> seedLess;} // you can specify setSeedLess function ($ seed) {$ this-> seedLess = $ seed; return true ;}} /*** the farmer class is used to obtain the instantiated fruit **/class farmer {// defines a static factory method public static function factory ($ fruitName) {switch ($ fruitName) {case 'apple': return new apple (); break; case 'grape': return new grape (); break; default: throw new badFruitException ("Error no the fruit ", 1); break ;}} class badFruitException extends Exception {public $ msg; public $ errType; public function _ construct ($ msg = '', $ errType = 1) {$ this-> msg = $ msg; $ this-> errType = $ errType;}/*** method for getting fruit instantiation */try {$ appleInstance = farmer :: factory ('apple'); var_dump ($ appleInstance);} catch (badFruitException $ err) {echo $ err-> msg. "_______". $ err-> errType ;}