工厂模式
单元素模式
观察者模式
命令链模式
策略模式
复制代码代码如下:
class people {
private $name = '';
private $user = null;
private function __constract($name){/*此处private定义辅助实现 单元素模式*/
$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/>我是老师,可以每天吃大餐。';
}
}