Three classes summarize PHP's five design patterns _php instance

Source: Internet
Author: User
Factory mode
Single element mode
Observer mode
Command chain mode
Policy mode
Copy Code code as follows:

class People {
Private $name = ';
Private $user = null;
Private Function __constract ($name) {//* Here Private defines the auxiliary implementation single element mode * *
$this->name = $name;
}
public static function instance ($name) {* * This method implements Factory mode * *
Static $object = null;/* This variable to implement a 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 variable implements the Observer mode * *
echo $who->work ()/* This method invokes the implementation policy mode.
}
}
Public Function on_action ($which = ' ") {
if (empty ($which)) echo ' ERROR ';
else {
foreach ($this->user as $user)
$user->action ($which);/* This method calls the implementation of 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 ' <br/> I am a student, facing nine to five. ';
}
function Action ($which) {
if (Method_exists ($this, $which)) return $this-> $which ();
else echo ' you are wrong! ';
}
Function Eat () {
Echo ' <br/> I am a student, can only eat the package. ';
}
}
Class Teacher {
function work () {
Echo ' <br/> I'm a teacher and I'm busy preparing for the evening. ';
}
function Action ($which) {
if (Method_exists ($this, $which)) return $this-> $which ();
else echo ' I can don't do it! ';
}
Function Eat () {
Echo ' <br/> I am a teacher, can eat a big meal every day. ';
}
}

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.