Three classes summarize the five design patterns for PHP

  • 2020-05-19 04:23:08
  • OfStack

The factory pattern
One element pattern
Observer mode
Command chain mode
The strategy pattern
 
class people { 
private $name = ''; 
private $user = null; 
private function __constract($name){/* here private Define an auxiliary implementation   One element pattern */ 
$this->name = $name; 
} 
public static function instance($name){/* This method implementation   The factory pattern */ 
static $object = null;/* This variable implementation   One element pattern */ 
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 implementation   Observer mode */ 
echo $who->work();/* This method calls the implementation   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 the implementation   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'm a student, chao 9 On the evening of 5 . '; 
} 
function action($which){ 
if (method_exists($this, $which)) return $this->$which(); 
else echo 'you are wrong!'; 
} 
function eat(){ 
echo '<br/> As a student, I can only eat set meals. '; 
} 
} 
class teacher { 
function work(){ 
echo '<br/> I'm a teacher. I'm busy preparing lessons in the evening. '; 
} 
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 eat a big meal every day. '; 
} 
} 

Related articles: