Concept Introduction:
Factory method Mode: Please read the simple Factory mode before learning the factory method mode
The factory method pattern is intended to define a factory interface that creates product objects, deferring actual creation to subclasses.
Factory method mode is a further abstraction and generalization of the simple factory model
Several required objects of the factory method pattern:
1. Abstract Factory
2, the specific factory: the implementation of the abstract factory interface listed methods, and each factory corresponding to their respective products
3. Abstract Products
4. Specific Products
Factory method pattern inside the orchard example, can be changed into a factory method mode, you can experiment with their own.
Case diagram:
code Example:
1<?PHP2 3 //This instance is written according to Nu WA's maker.4 5 //Define a global factory interface first6 //By the Yang of the yin rope to inherit all to achieve the method of lifting the rope7 Interfacenvwarope{8 Public functionLiftrope ($name);9 }Ten One //define a string to inherit Nvwarope A classYinropeImplementsnvwarope{ - Public functionLiftrope ($name){ - return NewBoy$name); the } - } - - //define Yang + classYangropeImplementsnvwarope{ - Public functionLiftrope ($name){ + return NewGirl$name); A } at } - - - //define an abstract interface for a person - Interfacepeople{ - Public functioneat (); in Public functiongetName (); - } to + - Abstract classAbstractpeopleImplementspeople{ the Private $name; * $ Public function__construct ($name){Panax Notoginseng $this->name =$name; - } the + Public functioneat () { A Echo $this->name. "Eat"; the } + - Public functionGetName () { $ Echo $this-name; $ return $this-name; - } - the //Check if there is a chest - Public functioncheckchest () {Wuyi return $this-havechest; the } - } Wu - classBoyextendsabstractpeople{ About Public $haveChest=false;//Boy without chest $ } - - classGirlextendsabstractpeople{ - Public $haveChest=true;//Girl with chest A } + the - $ //How to use the the //First get the example of a factory, i.e. a string or a rope. the $yinRope=NewYinrope (); the - $people=$yinRope->liftrope ("Zhang San"); in Echo $people-eat (); the Echo $people-getName (); the Var_dump($people->checkchest ());
PHP design mode-factory method mode (polymorphism Factory mode) (virtual construction sub-mode)