【php教程】PHP面向对象常规五种设计模式用三个类概括

2012-11-02 09:36 阅读 548 次 评论关闭

今天总结下PHP面向对象常规五种设计模式用三个类概括:工厂模式、单元素模式、观察者模式、命令链模式、策略模式。让你更深刻的了解PHP面向对象编程!猎微网友情分享PHP学习代码

PHP学习代码如下:

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/>我是老师,可以每天吃大餐。';
}
}

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:【php教程】PHP面向对象常规五种设计模式用三个类概括 | 猎微网

评论已关闭!