Three classes summarize the five design patterns of PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:16:53
Original
826 people have browsed it

Factory mode
Single element mode
Observer mode
Command chain mode
Strategy mode

Copy code The code is as follows:

class people {
private $name = '';
private $user = null;
private function __contract($name){/*Here private definition assists in implementing a single element Pattern*/
$this->name = $name;
}
public static function instance($name){/*This method implements the factory pattern*/
static $object = null; /*This variable implements single element mode*/
if (is_null($object))
$object = new people($name);
return $object;
}
public function work_in($who=null)
{
if (is_null($who)) echo 'error';
else {
$this->user[] = $who;/*this Array variables implement observer mode*/
echo $who->work();/*This method calls to implement strategy mode*/
}
}
public function on_action($which=' '){
if (empty($which)) echo 'error';
else {
foreach ($this->user as $user)
$user->action($ which);/*This method call implements the command chain mode*/
}
}
}
$people = people::instance('jack');
$people-> work_in(new student);
$people->work_in(new teacher);
$people->on_action('eat');
class student {
function work(){
echo '
I am a student, working 9 to 5. ';
}
function action($which){
if (method_exists($this, $which)) return $this->$which();
else echo 'you are wrong !';
}
function eat(){
echo '
I am a student and can only eat set meals. ';
}
}
class teacher {
function work(){
echo '
I am a teacher, and I am busiest preparing lessons at night. ';
}
function action($which){
if (method_exists($this, $which)) return $this->$which();
else echo 'i can not do it!';
}
function eat(){
echo '
I am a teacher and can eat big meals every day. ';
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325853.htmlTechArticleFactory mode Single element mode Observer mode Command chain mode Strategy mode Copy the code The code is as follows: class people { private $name = ''; private $user = null; private function __cons...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!