php設計模式之--組合模式

來源:互聯網
上載者:User

標籤:

php組合模式主要用於上下級關係,可以新增葉子和樹枝,分析如下代碼即可明白組合模式的含義:

<?phpheader(‘Content-Type:text/html;charset=utf-8‘);/** * 建立員工資訊抽象類別 */abstract class staff{    abstract function create();//建立員工資訊}/** * 建立部門資訊抽象類別 */abstract class department extends staff{    abstract function combine(staff $item);    abstract function chaifen(staff $item);}/** * 建立員工資訊實體類 */class createStaff extends staff{    private $name;    private $age;    private $sex;    private $staff = array();    public function __construct($name,$age,$sex)    {        $this->name = $name;        $this->age = $age;        $this->sex = $sex;    }    /**     * 建立員工資訊     */    public function create()    {        $this->staff[$this->name] = array(            ‘name‘=>$this->name,            ‘age‘=>$this->age,            ‘sex‘=>$this->sex,        );        return $this->staff;    }}/** * 建立部門關係 */class createDepartment extends department{    private $departmentname;//部門名稱    private $items = array();//用於存放人員資訊    private $depart_arr = array();//用於存放部門資訊    public function __construct($departmentname)    {        $this->departmentname = $departmentname;    }    public function create()    {        foreach($this->items as $item){            $arr = $item->create();            $this->depart_arr[$this->departmentname][] = $arr;        }        if(empty($this->depart_arr)){            $this->depart_arr[$this->departmentname] = array();        }        return $this->depart_arr;    }    /**     * 把傳進來的資訊放進items數組     */    public function combine(staff $item)    {        $this->items[] = $item;    }    /**     * 把傳進來的資訊刪除     */    public function chaifen(staff $item)    {        $key = array_search($item,$this->items);        if($key!==false){            unset($this->items[$key]);        }    }}$emploee1 = new createStaff(‘LHL‘,‘27‘,‘男‘);$emploee2 = new createStaff(‘XNN‘,‘26‘,‘男‘);$dep1 = new createDepartment(‘技術部‘);$dep1->combine($emploee1);$dep1->combine($emploee2);$emploee3 = new createStaff(‘MJ‘,‘22‘,‘男‘);$emploee4 = new createStaff(‘FJJ‘,‘22‘,‘女‘);$dep2 = new createDepartment(‘編輯部‘);$dep2->combine($emploee3);$dep2->combine($emploee4);$dep = new createDepartment(‘杏林譽苑‘);$dep->combine($dep1);$dep->combine($dep2);echo ‘<pre>‘;print_r($dep->create());echo ‘</pre>‘;

顯示效果如下

php設計模式之--組合模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.