The last time I used Starcraft to discuss basic object-oriented knowledge, it seems that object-oriented can solve many problems. However, there are still many problems, which cannot be solved too well simply by class and object. For example, how to determine the type of troops to be manufactured based on the player input (although it can be converted to other strings)? The basic object-oriented knowledge was discussed in Starcraft last time, it seems that object-oriented can solve many problems.
However, there are still many problems, which cannot be solved too well simply by class and object.
For example, how to determine the type of troops to be manufactured based on the player input (although it can be converted to another string), the player does not enter the code: new Marine ().
Like Starcraft, PHP does not have the ultimate weapon. If classes and interfaces are weapons, the design mode is your tactics and control. It allows you to win with the combination of various weapons.
The problem to be solved: in the personnel barracks, we rely on the input of the corresponding players to dynamically determine the type of troops to be created, for example, the gunshots and flame soldiers.
Idea: dynamically create a Class Object Based on the transmitted data.
Simple factory mode example:
We put the code of the machine gun class into a file, Marine. php. Its code is as follows:
We put the flame code into a file, Firebat. php. Its code is as follows:
The content of the main file is as follows:
Create ('marine'); $ troop1-> attack (); // create a machine gun object by receiving parameters $ troop2 = $ creator-> create ('firebat '); $ troop2-> attack ();?>
Purpose Summary: In the simple factory mode, you can encapsulate the tasks of the new object. Once you need to add a new return class, you only need to modify the part of the code that is responsible for creating the object.
Implementation Summary: a factory that automatically returns new objects based on parameters, for example, the BarracksCreator of the above-mentioned weapon maker. When using this tool, you only need to pass the parameters to its production method create (), no need to consider specific production details.