zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

PHP设计模式 三个 五种 概括
2023-06-13 09:14:35 时间
工厂模式
单元素模式
观察者模式
命令链模式
策略模式
复制代码代码如下:

classpeople{
private$name="";
private$user=null;
privatefunction__constract($name){/*此处private定义辅助实现单元素模式*/
$this->name=$name;
}
publicstaticfunctioninstance($name){/*此方法实现工厂模式*/
static$object=null;/*此变量实现单元素模式*/
if(is_null($object))
$object=newpeople($name);
return$object;
}
publicfunctionwork_in($who=null)
{
if(is_null($who))echo"error";
else{
$this->user[]=$who;/*此数组变量实现观察者模式*/
echo$who->work();/*此方法调用实现策略模式*/
}
}
publicfunctionon_action($which=""){
if(empty($which))echo"error";
else{
foreach($this->useras$user)
$user->action($which);/*此方法调用实现命令链模式*/
}
}
}
$people=people::instance("jack");
$people->work_in(newstudent);
$people->work_in(newteacher);
$people->on_action("eat");
classstudent{
functionwork(){
echo"<br/>我是学生,朝九晚五。";
}
functionaction($which){
if(method_exists($this,$which))return$this->$which();
elseecho"youarewrong!";
}
functioneat(){
echo"<br/>我是学生,只能吃套餐。";
}
}
classteacher{
functionwork(){
echo"<br/>我是老师,晚上备课最忙。";
}
functionaction($which){
if(method_exists($this,$which))return$this->$which();
elseecho"icannotdoit!";
}
functioneat(){
echo"<br/>我是老师,可以每天吃大餐。";
}
}