Three classes summarize the five design patterns of PHP
Release: 2016-07-25 09:06:46
Original
709 people have browsed it
Factory pattern
Single element mode
Observer mode
Command chain mode
Strategy Mode
- class people {
- private $name = '';
- private $user = null;
-
- private function __contract($name){/*The private definition here assists in the implementation of single element mode*/
- $this-> ;name = $name;
- }
-
- public static function instance($name){/*This method implements factory mode*/
- 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 variable implements the observer pattern*/
- echo $who->work();/*This method call implements the strategy pattern*/
- }
- }
-
- public function on_action($which=''){
- if (empty($which)) echo 'error';
- else {
- foreach ($this->user as $user)
- $user-> action($which);/*This method calls 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, heading towards Nine to five. ';
- }
-
- 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 in the evening preparing lessons. ';
- }
-
- 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. ';
- }
- }
Copy code
|
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31