Preface
==============================================================================
This PHP design mode album from the blog (jymoz.com), now has no access, this series of articles I have been looking for a long time to find the complete, thanks to the author Jymoz's Hard Pay Oh!
==============================================================================
The last time we discussed the basic object-oriented knowledge with StarCraft, it seems that object-oriented can solve many problems.
But there will be a lot of problems, simple to solve by class and object is not too good.
For example, how to determine the class to be manufactured based on what the player has entered (although it can be converted to another string), the player does not enter the code: New Marine ().
Like Interstellar, PHP does not have the ultimate class, if classes and interfaces are the same, then the design pattern is your tactics and control, it can let you rely on the various classes to win the match.
Problem to be solved: in the Clan barracks, we rely on the corresponding player input to dynamically determine the class to be created, assuming that the machine-gun soldiers and Pyro.
Idea: Dynamically based on the data passed, create a new object of the corresponding class.
Simple Factory Mode Example:
We put the machine gun class code into a file, marine.php, its code is as follows:
<? PHP class Marine { // method of attack by the gunner Public function attack () { echo ' Marine attack '; } }? >
We put the Pyro class code in a file, firebat.php, and its code is as follows:
<? PHP class Firebat { // Pyro Attack method public function attack () { Echo ' Firebat attack '; }? >
The contents of the main file are as follows:
<?PHP//classes for class maker classBarrackscreator {//the method of manufacturing the classes PublicCreate$createWhat) { //dynamically load the required class definition file according to the input parameters require_once($createWhat.‘. Php); //dynamically returns the object of the required class, based on the input parameters return New $createWhat; } } //creating a new Class Builder object $creator=Newbarrackscreator ();//Create a Pyro object by receiving parameters $troop 1=$creator->create (' Marine '); $troop 1-attack (); //Create a machine gun object by receiving parameters $troop 2=$creator->create (' Firebat '); $troop 2-attack ();?>
Usage Summary: Simple Factory mode encapsulates the task of the new object, and once you need to add a new return class, just modify the part of the code that is responsible for the new object.
Implementation summary: Requires a factory that automatically returns new objects based on parameters, such as the above class maker Barrackscreator, which only needs to pass parameters to his production method, create (), regardless of specific production details.
3. StarCraft PHP design mode-Simple Factory mode