|
單元素模式
觀察者模式
命令鏈模式
策略模式
復(fù)制代碼 代碼如下:
class people {
private $name = '';
private $user = null;
private function __constract($name){/*此處private定義輔助實(shí)現(xiàn) 單元素模式*/
$this->name = $name;
}
public static function instance($name){/*此方法實(shí)現(xiàn) 工廠模式*/
static $object = null;/*此變量實(shí)現(xiàn) 單元素模式*/
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;/*此數(shù)組變量實(shí)現(xiàn) 觀察者模式*/
echo $who->work();/*此方法調(diào)用實(shí)現(xiàn) 策略模式*/
}
}
public function on_action($which=''){
if (empty($which)) echo 'error';
else {
foreach ($this->user as $user)
$user->action($which);/*此方法調(diào)用實(shí)現(xiàn) 命令鏈模式*/
}
}
}
$people = people::instance('jack');
$people->work_in(new student);
$people->work_in(new teacher);
$people->on_action('eat');
class student {
function work(){
echo '<br/>我是學(xué)生,朝九晚五。';
}
function action($which){
if (method_exists($this, $which)) return $this->$which();
else echo 'you are wrong!';
}
function eat(){
echo '<br/>我是學(xué)生,只能吃套餐。';
}
}
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技術(shù):三個(gè)類概括PHP的五種設(shè)計(jì)模式,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。