三個類概括PHP的五種設計模式

來源:互聯網
上載者:User

原廠模式
單元素模式
觀察者模式
命令鏈模式
策略模式 複製代碼 代碼如下: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/>我是老師,可以每天吃大餐。';
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.