Three categories summarize five PHP design patterns
Factory model
Single element mode
Observer Mode
Command chain mode
Rule mode
- 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'
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'
I am a student and can only eat a package. ';
- }
- }
- Class teacher {
- Function work (){
- Echo'
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'
I am a teacher and can have a big meal every day. ';
- }
- }
|