PHP design mode: Factory mode
Intention:
Defines an interface for creating objects, letting subclasses decide which class to instantiate.
Factory mode implementation:
This interface is implemented by any factory class that creates objects in the Factory mode, and the method in the method body that implements the interface implements the methods in the interface, which declares the factory method that returns an object of type product.
Factory mode Application Scenario:
1, when a class does not know the class of the object it must create
2. When a class wants to specify the object it creates by its subclasses
3. When a class delegates the responsibility of creating an object to one of several helper subclasses, and you want to use which helper subclass is the agent this information is localized
Instance:
<?PHP/** Abstract Factory role*/InterfaceCreator { Public functionFactoryMethod ();} /** * Specific factory role a*/classConcretecreatoraImplementsCreator {/** * Factory method return specific product A * @return concreteproducta*/ Public functionFactoryMethod () {return Newconcreteproducta (); }} /** * Specific factory role B*/classConcretecreatorbImplementsCreator {/** * Factory method return specific product B * @return CONCRETEPRODUCTB*/ Public functionFactoryMethod () {return NewCONCRETEPRODUCTB (); }} /** Abstract Product role*/InterfaceProduct { Public functionoperation (); } /** * Specific product role a*/classConcreteproductaImplementsProduct {/** * Interface method implements output specific string*/ Public functionoperation () {Echo' Concreteproducta <br/> '; }} /** * Specific product role B*/classConcreteproductbImplementsProduct {/** * Interface method implements output specific string*/ Public functionoperation () {Echo' Concreteproductb <br/> '; }} classClient {/** * Main program. */ Public Static functionMain () {$creatorA=NewConcretecreatora (); $productA=$creatorA-FactoryMethod (); $productA-operation (); $creatorB=NewConcretecreatorb (); $productB=$creatorB-FactoryMethod (); $productB-operation (); }} Client::main ();?>