三个类概括PHP的五种设计模式

时间:2021-05-25

工厂模式
单元素模式
观察者模式
命令链模式
策略模式
复制代码 代码如下:
class people {
private $name = '';
private $user = null;
private function __constract($name){
$this->name = $name;
}
public static function instance($name){
static $object = null;
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;
echo $who->work();
}
}
public function on_action($which=''){
if (empty($which)) echo 'error';
else {
foreach ($this->user as $user)
$user->action($which);
}
}
}
$people = people::instance('jack');
$people->work_in(new student);
$people->work_in(new teacher);
$people->on_action('eat');
class student {
function work(){
echo '<br/>我是学生,朝九晚五。';
}
function action($which){
if (method_exists($this, $which)) return $this->$which();
else echo 'you are wrong!';
}
function eat(){
echo '<br/>我是学生,只能吃套餐。';
}
}
class teacher {
function work(){
echo '<br/>我是老师,晚上备课最忙。';
}
function action($which){
if (method_exists($this, $which)) return $this->$which();
else echo 'i can not do it!';
}
function eat(){
echo '<br/>我是老师,可以每天吃大餐。';
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章