Looking at PHP design pattern from Warcraft

Source: Internet
Author: User
Tags zend framework
Some time ago to see someone using Warcraft to explain the design pattern, feeling very interesting, so I changed it, and added some design mode content, issued today. Some places borrowed from the predecessors of the content, no note, please predecessors do not take it amiss ah.

Here we use the interesting Warcraft 3来 to discuss several common design patterns of PHP: Single piece mode, strategy mode, Factory mode, observer mode. Let's talk about these four today, and continue later.

These design patterns, are for object-oriented, so all with PHP5, and here I want to say is PHP4 from August 8, 2008 (I remember the same day as the Beijing Olympics, did not check, hehe) when the official issued the last PHP4 patch, which means that the era of PHP4 has ended, So, I suggest that you leave the PHP4 now, for PHP5.

One, single piece mode:

The question is presented as follows:

Some application resources are exclusive because there is only one resource of this type. For example, a connection through a database handle to a database is exclusive. You want to share the database handle in your application because it is an overhead when the connection is turned on or off, especially in the process of getting a single page.

Solution to the problem:

So let's start playing Warcraft now. First double-click War3.exe, this time began to run Warcraft. Let's do it in code.

<?php
Class War3
{

Public Function __construct ()

{

echo "War3 is Running.", "<br/>";

}
}
$war = new War3 ();

Run! Very well, the output

WAR3 is Running.

We can start the game now, but if I add it at the end of the code

$war 2 = new War3 ();

$war 3 = new War3 ();

What's going to happen? Let's try the output:

WAR3 is Running.

WAR3 is Running.

WAR3 is Running.

Finished, if you accidentally double-click two times on the opening of 3 Warcraft, if you double-click a few times, the computer must be blown off ... Let's figure out how to solve it.

Since we cannot instantiate this class so casually, we will change the constructor to a private method.

Class War3
{

Private Function __construct ()

{

echo "War3 is Running.", "<br/>";

}
}

But the private variables outside is inaccessible, so we can not even open the AH. Don't worry, we'll give him another one. Functions that are not accessible through instantiation, which is the static function,
Class War3
{

Private Function __construct ()

{

echo "War3 is Running.", "<br/>";

}

public static function Runwar ()

{

}
}

By using this static method Runwar () We control the instantiation of class War3, we still lack a previous identity, and we create an identity that indicates whether our class has been instantiated and, if instantiated, returns the handle directly.

Modify the class into

Class War3
{

protected static $_instance = NULL;

Private Function __construct ()

{

echo "War3 is Running.", "<br/>";

}

public static function Runwar ()

{

if (null = = Self::$_instance) {

Self::$_instance = new self ();

}


return self::$_instance;

}
}

Of course, the Instantiation of Warcraft when we run it also needs to be changed in a different way, through
$war = War3::runwar ();
You can start playing Warcraft, OK, the following is the complete code attached to:

<?php
Class War3
{

protected static $_instance = NULL;

Private Function __construct ()

{

echo "War3 is Running.", "<br/>";

}

public static function Runwar ()

{

if (null = = Self::$_instance) {

Self::$_instance = new self ();

}


return self::$_instance;

}
}

$war = War3::runwar ();
$war 2 = War3::runwar ();
$war 3 = War3::runwar ();

Run it, and the result is:

WAR3 is Running.

Too good, I double-click so many times, also only run a warcraft, now whatever you open, the machine will not explode.

This is the legendary unit price model, mainly used for a number of resources and instances only have an example of what is enough, for example, the Zend framework in the Zend_controller_front front-end controller, is the use of Unit price mode to design, You can look at that if you are interested.

Second, the strategic model:

The question is presented as follows:

In this pattern, the algorithm is extracted from the complex class and can be easily replaced. For example, if you want to change the way a page is arranged in a search engine, the policy mode is a good choice. Think about a few parts of the search engine--one that traverses the page, one part for each page, and the other based on the sorted results. In a complex example, these parts are in the same class. By using the policy pattern, you can place the arrangement part in another class to change the way the page is arranged without affecting the rest of the code for the search engine.

Solution to the problem:

Oh, not so complicated, just now the Warcraft finally opened, we still play Warcraft good.
Here we choose Battle, wow a lot of races, people (Human), Orcs (ORC), Night Elves (Nighy elf), Undead (undead). I choose the Elves (Nighy elf), and then choose an Elf clan and two orcs (ORC), one orc and I, the other elves and orcs, another family.

Each player will get some resources after entering the game, such as a hall, five elves (drudgery) and a mine. These can be called initialization things, where we can use the policy pattern to encapsulate these initializations.

To get to the point, first we build a player class:

<?php
Class player
{

Player name

protected $_name;

Race

protected $_race;

Team

protected $army;

Building

protected $building;

Population

protected $population;

Gold

protected $gold;

Wood

protected $wood;

constructors, setting the race of the owning

Public function __construct ($race)

{

$this->race = $race;


}

__get () method to get protection properties

Private Function __get ($property _name)

{

if (Isset ($this-> $property _name)) {

Return ($this-> $property _name);

}

else {

return (NULL);

}

}

__set () method to set protection properties

Private Function__set ($property _name, $value)

{

$this-> $property _name= $value;

}
}

Next, we build a player-initialized interface,

<?php
Interface Initialplayer
{

Create an initialized force

Public Function Givearmy ($player);

Build the building that is initialized

Public Function givebuilding ($player);

Initializing resources

Public Function Givesource ($player);
}

Well, here's what we're going to do with this interface, and for the sake of convenience, I've chosen only two races, just to write the initialization of these two races:

The first is the Elvish clan:

<?php
Class Nighyelfinitial implements Initialplayer
{

Create an initialized force

Public Function Givearmy ($player)

{

Five Little elves.

For ($i =0 $i <=5; $i + +)

{

$creator = new Creatarms ()//This is to create the Force class, in the back of the factory model will be used, here I don't say more

$player->army[] = $creator->creat (' Wisp ', './arms/');

}

}

Build the building that is initialized

Public Function givebuilding ($player)

{

$creator = new Creatbuildings ();

A base

$player->building[] = $creator->creat (' townhall ', './buildings/');

A mine

$player->building[] = $creator->creat (' Mine ', './buildings/');

}

Initialize the population limit

Public Function Givesource ($player)

{

$player->population= 10;

$player->gold= 1000;

$player->wood= 100;

}
}

Then came the Orcs:

<?php
Class Orcinitial implements Initialplayer
{

Create an initialized force

Public Function Givearmy ($player)

{

Five drudgery.

For ($i =0 $i <=5; $i + +)

{

$creator = new Creatarms ()//This is to create the Force class, in the back of the factory model will be used, here I don't say more

$player->army[] = $creator->creat (' Peon ', './arms/');

}

}

Build the building that is initialized

Public Function givebuilding ($player)

{


$creator = new Creatbuildings ();

A base

$player->building[] = $creator->creat (' townhall ', './buildings/');

A mine

$player->building[] = $creator->creat (' Mine ', './buildings/');

}

Initialize the population limit

Public Function Givesource ($player)

{

$player->population= 10;

$player->gold= 1000;

$player->wood= 100;

}
}



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.