This article introduces the content of the PHP design model of the builder model, has a certain reference value, now share to everyone, the need for friends can refer to
Builder Mode (creator) is a pattern that I think is difficult to understand in the creation mode.
The builder pattern and the abstract factory pattern are a bit similar to creating combinations, but there are many abstract factories, and builders are not used.
The builder pattern is characterized by separating the creation and presentation.
To continue with the game as an example, when we play the game to create a hero, first to abstract an abstract builder class, and then all the heroes inherit this abstract class. And the Hero class is the hero's representation class, separated from the creation, all heroes can be represented by this class.
If you need to add a hero directly to a class Guanyu classes just like, switch on the client.
The recording code is as follows:
<?php Class Hero {//skill public $_skill; Weapon public $_weapon; Mount Public $_horse; /** Hero Expression method, different heroes and different representations * display */function Display () {echo "trick is: {$this->_skill}" ; echo "Weapon is: {$this->_weapon}"; echo "mount is: {$this->_horse}"; }}/** Hero Builder abstract class * Abstraction Herobuilder */abstract class Herobuilder {protected $_hero; function __construct () {$this->_hero = new Hero (); }//Abstract hero Trick method abstract function Heroskill (); Abstract Hero Weapon method, abstract function heroweapon (); Abstract Hero Mount method, abstract function herohorse (); Create Heroic method abstract function Createhero (); /** Guan Yu Hero class inherits abstract class must complete abstract method * Guanyu */class Guanyu extends Herobuilder {function Heroskill () { $this->_hero->_skill = "tow meter <br/>"; } function Heroweapon () {$this->_HERO->_weapon = "tsing Lung yan Yue Dao <br/>"; } function Herohorse () {$this->_hero->_horse = "Red rabbit horse <br/>"; } function Createhero () {return $this->_hero; }}/** Hero interface class * HEROAPI */class Heroapi {function Create ($_obj) {$_obj->heroskill (); $_obj->heroweapon (); $_obj->herohorse (); return $_obj->createhero (); } }
<?php //Builder Mode index.php header ("Content-type:text/html;charset=utf-8"); Require_once "builder.php"; Hero Interface class $obj = new Heroapi (); Create what you want to use when creating a Guan Yu Hero object $guanyu = new Guanyu (); Create join battlefield $guanyuhero = $obj->create ($guanyu); echo "Guan Yu joins the battlefield <br/>"; $guanyuhero->display ();//Show
Output Result:
Guan Yu joins the battlefield
The trick is: Tow tool gauge
The weapon is: Tsing Lung Yan Yue Dao
The mount is: Red Rabbit horse
Related recommendations:
Prototype mode of PHP design mode
PHP design mode single-instance mode