Three classes summarize the five design patterns of PHP

WBOY
Release: 2016-07-25 09:06:46
Original
693 people have browsed it
Factory pattern
Single element mode
Observer mode
Command chain mode
Strategy Mode
  1. class people {
  2. private $name = '';
  3. private $user = null;
  4. private function __contract($name){/*The private definition here assists in the implementation of single element mode*/
  5. $this-> ;name = $name;
  6. }
  7. public static function instance($name){/*This method implements factory mode*/
  8. static $object = null;/*This variable implements single element mode*/
  9. if (is_null( $object))
  10. $object = new people($name);
  11. return $object;
  12. }
  13. public function work_in($who=null)
  14. {
  15. if (is_null($who)) echo 'error';
  16. else {
  17. $this->user[] = $who;/*This array variable implements the observer pattern*/
  18. echo $who->work();/*This method call implements the strategy pattern*/
  19. }
  20. }
  21. public function on_action($which=''){
  22. if (empty($which)) echo 'error';
  23. else {
  24. foreach ($this->user as $user)
  25. $user-> action($which);/*This method calls to implement the command chain mode*/
  26. }
  27. }
  28. }
  29. $people = people::instance('jack');
  30. $people->work_in(new student);
  31. $people->work_in(new teacher);
  32. $people->on_action('eat');
  33. class student {
  34. function work(){
  35. echo '
    I am a student, heading towards Nine to five. ';
  36. }
  37. function action($which){
  38. if (method_exists($this, $which)) return $this->$which();
  39. else echo 'you are wrong!';
  40. }
  41. function eat(){
  42. echo '
    I am a student and can only eat set meals. ';
  43. }
  44. }
  45. class teacher {
  46. function work(){
  47. echo '
    I am a teacher, and I am busiest in the evening preparing lessons. ';
  48. }
  49. function action($which){
  50. if (method_exists($this, $which)) return $this->$which();
  51. else echo 'i can not do it!';
  52. }
  53. function eat(){
  54. echo '
    I am a teacher and can eat big meals every day. ';
  55. }
  56. }
Copy code


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!