Three categories summarize five PHP design patterns

Source: Internet
Author: User

Factory Model
Single element mode
Observer Mode
Command Chain Mode
Rule Mode
Copy codeThe Code is as follows:
Class people {
Private $ name = '';
Private $ user = null;
Private function _ constract ($ name) {/* Here private defines the mode to assist in implementing a single element */
$ This-> name = $ name;
}
Public static function instance ($ name) {/* This method implements the factory mode */
Static $ object = null;/* this variable implements the 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 ();/* Implementation Policy mode of this method call */
}
}
Public function on_action ($ which = ''){
If (empty ($ which) echo 'error ';
Else {
Foreach ($ this-> user as $ user)
$ User-> action ($ which);/* call this method to implement 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, 9 to 5. ';
}
Function action ($ which ){
If (method_exists ($ this, $ which) return $ this-> $ which ();
Else echo 'you are wrong! ';
}
Function eat (){
Echo '<br/> I am a student and can only use a package. ';
}
}
Class teacher {
Function work (){
Echo '<br/> I am a teacher and have the busiest time 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 '<br/> I am a teacher and can have 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.