From lightsaber in the StarCraft design mode of PHP)

Source: Internet
Author: User
Tags blizzard

1-simple factory Mode

If you are not familiar with object-oriented programming, we recommend that you first use the StarCraft Quick Start PHP object-oriented programming.
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 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:

<? PHP
Class marine {
// Method of cyberattack
Public Function attack ()
{
Echo 'Marine attack ';
}
}
?>

We put the flame code into a file, firebat. php. Its code is as follows:

<? PHP
Class firebat {
// Method of flame soldier attack
Public Function attack ()
{
Echo 'firebat attack ';
}
}
?>

The content of the main file is as follows:

<? PHP
// Category of weapon manufacturers
Class barrackscreator {
// Method for manufacturing the arms
Public create ($ createwhat)
{
// Dynamically load the required class definition file based on input parameters
Require_once ($ createwhat. '. php ');
// Return the required class objects dynamically based on input parameters
Return new $ createwhat;
}
}

// Create a new category maker object
$ Creator = new barrackscreator ();

// Create a flame object by receiving Parameters
$ Troop1 = $ creator-> 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.

/*************************************** ************************/

2-factory method mode

The factory model mentioned in the PHP manual is actually a simple factory model. Here we will discuss the extension of the simple factory model: the factory method model.
The problem to be solved: although the simple factory solves the problem of dynamically returning different types of objects, in actual situations, some additional processing is often required when creating an object, for example, when creating a machine gun, you need to determine whether the crystal mine is greater than 50, while when creating a flame soldier, you need to determine whether the crystal mine is greater than 50 and the gas mine is larger than 25, and whether the research institute has been built. If you put all the code in the factory manufacturing class, it will make the manufacturing class Very bloated, and as the factory produces more and more types of objects, the factory manufacturing class code will become increasingly difficult to maintain.

Idea: In the simple factory model, the factory class (the class of the weapon manufacturer) remains unchanged, and a manufacturing interface is added to define a method for the actual manufacturing object, then define the factories for specific manufacturing objects and require these factories to execute this manufacturing interface so that these factories can implement the actual manufacturing objects.

Factory method mode example:
We put the code of the machine-gun class and the machine-gun-making class into a file, Marine. php. Its code is as follows:
<? PHP
// Machine-gun
Class marine {
// Method of cyberattack
Public Function attack ()
{
Echo 'Marine attack ';
}
}
// Creates the class of the host and executes the abstractcreator interface.
Class marinecreator implements extends actcreator {
// Method for creating a machine gun
Public Function realcreate ()
{
// If the crystal ore is greater than 50, here is just a description, because there is no ore variable, and the processing of the crystal less than 50 is not considered.
If ($ ore> 50)
{
Return new marine ();
}
}
}
?>
We put the code of the flame soldier class and the class for creating the flame soldier into a file, firebat. php. Its code is as follows:
<? PHP
// Flame soldiers
Class firebat {
// Method of flame soldier attack
Public Function attack ()
{
Echo 'firebat attack ';
}
}
// Class for creating flame soldiers. The execution interface is abstractcreator.
Class firebatcreator implements extends actcreator
// Method for creating a flame soldier
Public Function realcreate ()
{
// If the crystal mine is larger than 50 and the gas mine is larger than 25, and the research institute already exists. Here is just a description, because there are no ore, gas, and Academy variables, and processing is not considered when resources are insufficient.
If ($ ore> 50 & $ gas> 25 & Academy> 1)
{
Return new firebat ();
}
}
}
?>

The content of the main file is as follows:
<? PHP
// Interfaces that must be executed by specific factories
Interface abstractcreator {
// Define the implementation methods of specific factories
Public Function realcreate ();
}
// Category of the arms manufacturer, that is, the main factory
Class barrackscreator {
// Method for manufacturing the arms
Public create ($ createwhat)
{
// Dynamically load the required class definition file based on input parameters
Require_once ($ createwhat. '. php ');
// Dynamically obtain the name of the corresponding factory class based on the input parameters
$ Creatorclassname = $ createwhat. 'creator ';
// Create a specific factory object
$ Creator = new $ creatorclassname;
// Use a factory for actual production, and then return the object of the required class. Because they all execute the interface abstractcreator, The realcreate () method must be implemented ()
Return $ creator-> realcreate ();
}
}
// Create a new category maker object
$ Creator = new barrackscreator ();
// Create a flame object by receiving Parameters
$ Troop1 = $ creator-> Create ('marine ');
$ Troop1-> attack ();

// Create a machine gun object by receiving Parameters
$ Troop2 = $ creator-> Create ('firebat ');
$ Troop2-> attack ();
?>

Purpose Summary: In the factory method mode, the task of creating a new object is assigned to the corresponding factory class. You do not need to modify the external main factory because some production objects need to be processed.
Implementation Summary: The main factory class that needs to receive parameters, such as the barrackscreator of the above arms manufacturer, also needs to declare an interface of the specific manufacturing method, such as abstractcreator above, then define the specific factory classes for each product. Each specific factory class must execute the interface abstractcreator, so that they must implement the method of manufacturing objects, such as the realcreate () above (). When used, you only need to pass the parameter to the production method create () of the main factory class factory, and then create () generates the object of the specific factory class according to the parameter, and call the specific factory class realcreate () to obtain the manufacturing product object and return it. for external use, you only need to call the main factory class factory for production.

Note: in fact, the factory method mode in this article is different from that written in some articles. The standard factory mode often uses an abstract class to replace the aforementioned interface abstractcreator, then let all the specific factory classes inherit it, but when using it, because the abstract class cannot be instantiated (the object to create it), it is often because the Code directly new firebatcreator (), however, the simple factory mode can solve the problem of direct new, so I will use the simple factory mode and the factory method mode here to make the example more practical. At the same time, because PHP is a single inheritance, and there is no limit on the number of interfaces executed, the use of the interface abstractcreator is more flexible.

/*************************************** ************************/

3-Abstract Factory Model

Starcraft is a strategic game, so the enemy and I are different in the same way.
The typical color is the mouse color. When you click your own object, the mouse color turns green. When you click an enemy object, the mouse color turns red.
There is also the state of each object. when an object is in a vertex, the state area shows the complete state. When an enemy object is in a vertex, some information is displayed in the state area.
Let's assume that we only consider the mouse and the transportation ship of the person family. After the player's transport ship points, the status area will show the troops loaded inside, while the enemy in the point will not show whether the troops are loaded inside.

In this way, we have four types of objects: point your mouse, point your enemy's mouse, your own transport ship status, and the enemy's transport ship status.
If we use the factory method mode, we need to establish four specific factories (or sub-factories). Such code is not easy to maintain and modify, because we will add another situation: allies in the future.
Problem to be solved: we hope to associate these objects to make the operations in the factory more logical.
Idea: Since we distinguish objects by ourselves and our enemies, we put the objects that belong to them in the same specific factory, and each specific factory is responsible for manufacturing multiple objects.
Example of the abstract factory mode:
<? PHP
// Four product categories
// Mouse when you click your own object
Class minemouse {
// Mouse color
$ Color = 'green ';
}
// Mouse when an enemy object is clicked
Class enemymouse {
// Mouse color
$ Color = 'red ';
}
// Your own shipping status
Class minedropship {
// Display the loading status. Assume 2 tanks
$ Loading = '2 tank ';
}
// The enemy's transport ship status
Class enemydropship {
// Do not display the loading status
$ Loading = '';
}
// Master factory class, also called abstract factory class
Class abstractcreator {
// Allocate work to a specific factory based on parameters and return the specific factory object
Public Function getcreator ($ belong)
{
// Obtain the class name of a specific factory
$ Creatorclassname = $ belong. 'creator ';
// Return the specific factory object
Return new $ creatorclassname ();
}
}
// Interface required by the specific factory
Interface productcreator {
// Manufacturing method, or return the product (mouse, transport ship) method based on parameters
Public Function creatproduct ($ productname );
}
// Execute the interface to create a specific factory for your own objects
Class minecreator implements productcreator {
// Generate and return your own product based on the parameter
Public Function creatproduct ($ productname)
{
// Obtain the product class name
$ Productclassname = 'Mine '. $ productname;
// Return the product object
Return new $ productclassname;
}
}
// Create a factory for the enemy's objects and execute the interface
Class enemycreator implements productcreator {
// Generate and return products belonging to enemies based on parameters
Public Function creatproduct ($ productname)
{
// Obtain the product class name
$ Productclassname = 'Choose '. $ productname;
// Return the product object
Return new $ productclassname;
}
}
// Start the operation
// Create an abstract factory object
$ Abstractcreator = new abstractcreator ();
// Obtain the specific factory object based on the ownership. Here we will first demonstrate the enemy's
$ Realcreator1 = $ abstractcreator-> getcreator ('enable ');
// Let the specific factory object produce the mouse object
$ Product1 = $ realcreator1-> creatproduct ('mouse ');
// Display the color and red of the mouse object
Echo $ product1-> color;

// Obtain another specific factory object based on the ownership. Here, we will demonstrate our own
$ Realcreator2 = $ abstractcreator-> getcreator ('Mine ');
// Let specific factory objects produce transport ships
$ Product2 = $ realcreator2-> creatproduct ('dropship ');
// Display the loading object for the transport ship object. The result is 2 tanks and 2 tanks.
Echo $ product2-> loading;
?>
Purpose Summary: Abstract Factory model classifies products with the same attributes into the same factory to reduce the number of specific factories and clarify their responsibilities during operations.
Implementation Summary: an abstract factory that returns a specific factory object based on the property, such as abstractcreator above. At the same time, you need to classify the attributes of each product (your own, your enemy, create a specific factory based on the properties, and each factory creates multiple products with the same properties (mouse and transport ship ).

/*************************************** ************************/

4-single-piece and single-State Modes

StarCraft allows players to cheat. Of course, this is the time to compete with computers. Moreover, cheating has a special feature, such as rapid construction. unlimited energy is effective for all players (including computers). If cheating is disabled, the effects on all players will disappear at the same time.
This means that if we take the cheating status as a class, we can only have one object.
Problem to be solved: make sure that a class can only have one object.
Idea: revoke the permissions of newly created objects, including new and clone. To prevent override of methods and members of the parent class by subclass, set the class to final. Use static members to save Unique objects
Single-piece mode example:
<? PHP
// Set the class to final and prohibit other classes from inheriting it
Final class cheat {
// The effective status of the quick build, protected by private
Private $ fastbuild = false;
// Use static members to save Unique objects
Private Static $ instance;
// Set the effective state of the quick build. Use public to make public calls.
Public Function setstatus ($ input)
{
// If the entered secret is correct, Operation cwal is the secret for quick Building
If ($ input = 'Operation cwal ')
{
// Reverse the status like a switch
$ This-> fastbuild =! $ This-> fastbuild;
}
}
// Read the method of the effective state of the quick build. Use public to make public calls.
Public Function getstatus ()
{
Return $ this-> fastbuild;
}
// Obtain the unique method of the unique object
Public Function getinstance ()
{
// If the object is not created, create it
If (! Isset (SELF: $ instance ))
{
SELF: $ instance = new cheat ();
}
Return self: $ instance;
}
// Use private to prohibit new objects other than this class
Private function _ construct (){}
// Use private to prohibit clone objects outside of this class
Private function _ clone (){}
}
// The Only Way to obtain cheating objects
$ Cheatinstance = cheat: getinstance ();
// The current output is 0 (this is related to the operating system, and some may output false. It is best to use var_dump instead of ECHO)
Echo $ cheatinstance-> getinstance ();
// Enter the secret
$ Cheatinstance-> setinstance ('Operation cwal ');
// Now the output is 1 (this is related to the operating system, and some may Output True, it is best to replace echo with var_dump)
Echo $ cheatinstance-> getinstance ();
// Enter the cheats again to cancel cheating
$ Cheatinstance-> setinstance ('Operation cwal ');
// Now the output is 0 again (this is related to the operating system, some may output false, it is best to replace echo with var_dump)
Echo $ cheatinstance-> getinstance ();
?>

There are some special secrets in the space, such as invincible and increased mining. This is only useful to human players and has no effect on computer players (everyone is invincible and how to play ). We hope that there will be a class of human cheating to inherit the class of cheating, and some new cheats in the subclass, such as invincible. The single-piece mode does not allow inheritance. We can use the single-State mode.
The single-State mode is not consistent by a unique object. It sets the relevant members to static, so that even if many objects exist, they share members and keep their States consistent. Inheritance is also allowed.
<? PHP
// If final is not used, inheritance is allowed.
Class cheat {
// The effective state of the quick build. use private protection and set static to share all cheating objects.
Private Static $ fastbuild = false;
// Set the effective state of the quick build. Use public to make public calls.
Public Function setstatus ($ input)
{
// If the entered secret is correct, Operation cwal is the secret for quick Building
If ($ input = 'Operation cwal ')
{
// Reverse the status like a switch
SELF: $ fastbuild =! SELF: $ fastbuild;
}
}
// Read the method of the effective state of the quick build. Use public to make public calls.
Public Function getstatus ()
{
Return self: $ fastbuild;
}
}

// Add a cheating object
$ Cheatinstance1 = new cheat ();
// The current output is 0 (this is related to the operating system, and some may output false. It is best to use var_dump instead of ECHO)
Echo $ cheatinstance1-> getinstance ();
// Enter the secret
$ Cheatinstance1-> setinstance ('Operation cwal ');
// Now the output is 1 (this is related to the operating system, and some may Output True, it is best to replace echo with var_dump)
Echo $ cheatinstance1-> getinstance ();
// Add a cheating object
$ Cheatinstance2 = new cheat ();
// Now the output is also 1 because they share $ fastbuild
Echo $ cheatinstance2-> getinstance ();
?>
Some members can be added to the subclass of cheating.
Single-piece mode usage Summary: ensures the uniqueness of a Class Object and is often used to save system resources, such as preventing repeated database connections.
Summary of the single-piece mode: revokes all the right to create an object, puts the object into a private member of the class, and provides only one method for creating a new object. When calling this method, you can determine whether the object has been created.

Summary of the usage of the single-State mode: ensure that all objects in a class are consistent, and allow flexible inheritance of these types. However, compared with the single-piece mode, the system resource overhead is larger.
Summary of single-State mode: Set all related members to static.

/*************************************** ************************/

5-template Mode

The zerg troops in the interstellar industry have a special evolutionary weapon, namely, the Flying Dragon. The flying dragon can become an Air Guard (tiancrab) or a swallowed-up (to the air ). In addition, there is also the ability to evolve into a ground thorn.
The three changes are similar: the changed original troops disappear, produce an egg or cocoon, hatch for a while, the eggs disappear, and new troops are generated.

If we develop these three evolution independently, We will generate duplicate code, and the redundancy will increase. Therefore, we need to try to reduce unnecessary code.
The problem to be solved: the same steps are required, but the details of each step are different.

Idea: to build an evolutionary Engineering Framework, we only need to control details.
Template mode example:
<? PHP
// Evolutionary framework class, which is an abstract class
Abstract class evolution {
// Framework method, which implements each step and uses final to prohibit subclass coverage
Final public function process ($ troop)
{
Generate an egg and the parameter is an evolutionary unit.
$ Egg = $ this-> becomeegg ($ troop );
Waiting for egg hatching, parameter: Egg
$ This-> waitegg ($ egg );
Generate new troops after hatching
Return $ this-> becomenew ($ egg );
}
The following three abstract methods are implemented by specific subclasses.
Abstract Public Function becomeegg ($ troop );
Abstract Public Function waitegg ($ egg );
Abstract Public Function becomenew ($ egg );
}
Here, we use the evolution class of the Sky Guard (tiancrab) to demonstrate the solution of the ground thorn and so on.
// The Evolutionary class of crab inherits the abstract evolutionary class
Class guardianevolution extends evolution {
// Generate an egg
Public Function becomeegg ($ troop)
{
// Destroy the Flying Dragon and return the code of an egg object
}
// Waiting for egg hatching
Public Function waitegg ($ troop)
{
// Wait for dozens of seconds for the code
}
// Generate new troops after hatching
Public Function becomenew ($ troop)
{
// Destroy the egg and return a crab
}
}
// Create a new evolutionary crab object
$ E1 = new guardianevolution ();
// Let it call the evolution framework function of the parent class to automatically complete three steps
$ E1-> process ($ SDS );
?>

Summary: The template mode can automate a series of steps while meeting different details.
Implementation Summary: an abstract class is required to include a framework function, so that a specific subclass can inherit it and implement all the steps. You only need to call the framework function automatically.

/*************************************** ************************/

6-positive mode

All the battles in interstellar are on maps. As long as we can edit maps, we can create new battles. However, if the Code related to map creation in the interstellar space is open, it is estimated that most people do not understand it, let alone editing the map themselves.

The problem to be solved: if you do not know the structure of the map code, we need players to edit the map themselves.

Train of Thought: For players, he is familiar with the shape of crystal mines and highlands. He interacts with the system through the mouse. We can design a map editor for gamers to use without having to study the map
Detailed code. (In fact, blizzard is doing this. Many gamers and even blizzard insiders use the map editor in the space)

Facade example:
<? PHP
// The player's mouse object, which records the status of the mouse in editing
Class mouse {
// The X-axis coordinate of the mouse
Public static $ X;
// The objects that can be drawn with the mouse, such as crystal mines and rivers
Public static $ object;
// Y axis of the mouse
Public static $ Y;
}
// Map editor
Class mapedit {
// Draw Method
Public static function draw ()
{
// Draw various things on the map based on the state of the mouse object
// If it is a crystal mine
If (mouse: $ object = "ore ")
{
// Call the method of drawing the crystal mining class. This class is defined below. This is a real drawing, but the player does not have to learn his details.
Ore: Draw ();
// If it is a river
} Elseif (mouse: $ object = "River "){
// Call the river class plotting method. This class is defined below. This is a real painting, but the player does not have to learn his details.
River: Draw ();
}
}
}
// Crystal Mining
Class ore {
// The remaining mines and other attributes are skipped here
Public $ remain;
// Draw a crystal mine
Public static function draw ()
{
// Actually draw the bottom layer detailed code of the crystal mine
}
}
// Rivers
Class river {
// Draw a river
Public static function draw ()
{
// Actually draw the bottom layer details code of the river
}
}

// The Player clicks the crystal mining object on the Drawing Object List in the map editor.
Mouse: $ object = "ore ";
// Move the mouse
Mouse: $ x = 311;
Mouse: $ Y = 126;
// Click on the map to draw the current object, that is, a crystal mine.
Mapedit: Draw ();
?>

Conclusion: The positive mode allows users to focus on the work they want, without having to know all the details, or providing an easy-to-use tool, while shielding the underlying details, users do not have to learn it again.
Implementation Summary: A Code class similar to the above map editor is required to help gamers conveniently perform operations.

/*************************************** ************************/

7-Observer Mode

When we open a map in the space to fight with several computers, several players on the computer are equivalent to an alliance. Once we attack a computer, other computers will be rescued.
So how can we let Computers know that their allies have been attacked? And automatically respond?
The problem to be solved: Once a computer is attacked by us, other computers will be known and automatically dispatched for rescue.
Idea: Set up some additional observation systems for the computer to notify other computers.

Observer (observer) mode example:
<? PHP
// Abstract Association class
Abstract class abstractally {
// Place the set of observers. The simple array is used for demonstration.
Public $ oberservercollection;
// Add the observer method. The parameter is the name of the observer (also a player ).
Public Function addoberserver ($ oberservername)
{
Put the observer object into the set of the observer as an element
$ This-> oberservercollection [] = new oberserver ($ oberservername );
}
// Notify the observer of the name of the attacked computer
Public Function Policy ($ beattackedplayername)
{
// Loop the set of observers
Foreach ($ this-> oberservercollection as $ oberserver)
{
// Call the rescue function of each observer. The parameter is the name of the attacked computer. If is used to exclude the observer of the attacked computer
If ($ oberserver-> name! = $ Beattackedplayername) $ oberserver-> help ($ beattackedplayername );
}
}
Abstract Public Function beattacked ($ beattackedplayer );
}
// Specific Alliance class
Class ally extends abstractally {
// Constructor, which takes the array of names of all computer players as parameters
Public Function _ construct ($ allplayername)
{
// Loop the array of all computer players
Foreach ($ allplayername as $ playername)
{
// Add an observer. The parameter is the name of each computer player.
$ This-> addoberserver ($ playername );
}
}
// Notify the observer of the name of the attacked computer
Public Function beattacked ($ beattackedplayername)
{
// Call the rescue function of each observer. The parameter is the name of the attacked computer. If is used to exclude the observer of the attacked computer
$ This-> Policy ($ beattackedplayername );
}
}
// Observer Interface
Interface ioberserver {
// Define standard Rescue Methods
Function help ($ beattackedplayer );
}
// Specific observer class
Class oberserver implements ioberserver {
// The Name Of The Observer (also a player) object
Public $ name;
// Constructor. The parameter is the name of the observer (also a player ).
Public Function _ construct ($ name)
{
$ This-> name = $ name;
}
// How the observer performs rescue
Public Help ($ beattackedplayername)
{
// The simple output here, who is going to save and add a line feed to facilitate display
Echo $ this-> name. "Help". $ beattackedplayername. "<br> ";
}
Abstract Public Function beattacked ($ beattackedplayer );
}
// Assume that I have a pair of three, two worms, and one genius.
$ Allcomputeplayer = array ('zerg1', 'protoss2', 'zerg2 ');
// Create a computer Alliance
$ Ally = new ally ($ allcomputeplayer );
// Suppose I attacked the second Zerg.
$ Ally-> beattacked ('zerg2 ');
?>

Purpose Summary: The Observer mode can immediately notify all related objects of a state change and call the processing method of the other party.
Implementation Summary: An observer class is required to handle changes. The observed object must implement a method to notify all observers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.