This article introduces the content of the PHP design model of the factory method, has a certain reference value, now share to everyone, the need for friends can refer to
Today focused on the factory method (FactoryMethod) This design model, the following are some of their own learning experience and experience, to make a record:
The factory method belongs to one of the 23 modes of creation, and because of the previous knowledge of the simple factory, and the factory method is an evolution of a simple factory, it can be seen from a simple factory that a class interacting with the client to assume the creation of several different classes, is a rather tiring process, The factory method is to split the interaction class on its basis so that each class can be created independently for horizontal expansion.
To create a game role, for example:
<?php/** Hero * Hero interface */interface Hero {function Create (); }/** Guanyu Guan Yu * Specific Hero class */class Guanyu implements Hero {function Create () {echo] Guan Yu joins the battlefield. 。。 <br/> "; }}/** Zhangfei Zhang Fei * Specific Hero class */class Zhangfei implements Hero {function Create () {echo "Zhang Fei Plus Into the battlefield ... <br/> "; }}/** FactoryMethod * Factory Method interface */interface FactoryMethod {function Createhero (); }/** guanyufactory * Guan Yu Factory class */class Guanyufactory implements FactoryMethod {function Createhero () { return new Guanyu (); }}/** Zhangfeifactory * Zhang Fei factory class */class Zhangfeifactory implements FactoryMethod {function Createhero () {return new Zhangfei (); } }
<?php//factory-style client index.php header ("Content-type:text/html;charset=utf-8") ; Require_once "factorymethod.php"; Each call their own factory method to create the $GYF = new Guanyufactory (); $ZFF = new Zhangfeifactory (); Call the Create Hero method of the respective factory method $GuanYu = $GYF->createhero (); $ZhangFei = $ZFF->createhero (); Call the respective Create Hero Method $GuanYu->create (); $ZhangFei->create ();