Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

PHP 設計模式:建造者模式

什麼是建造者模式

建造者模式主要是為了消除其他物件複雜的建立過程。

設計情境

  1. 有一個 UserInfo 類別,建立它需要準備姓名、年齡、金錢等資訊,才能得到完整的使用者結果。
  2. 再建一個 UserInfoBuilder 使用者建造者類別,把 UserInfo 複雜的建立步驟封裝起來,簡化呼叫端。

沒有建造者時:建立過程痛苦

<?php
// 建造者模式,目的是消除其它物件複雜的創建過程

/* 描述一個用戶的類,包含姓名、年齡、金錢 */
class UserInfo {

    protected $userName = '';
    protected $userAge = '';
    protected $userMoney = '';

    public function setUserName($userName) {
        $this->userName = $userName;
    }

    public function setUserAge($userAge) {
        $this->userAge = $userAge;
    }

    public function setUserMoney($userMoney) {
        $this->userMoney = $userMoney;
    }

    public function getPeople() {
        echo "這個人的姓名是:" . $this->userName . ',年齡是:'
             . $this->userAge . ', 金錢:' . $this->userMoney;
    }
}

/* 實例化並建立用戶時,必須逐步設定各項資訊 */
$peopleInfo = array(
    'userName'  => 'initphp',
    'userAge'   => 28,
    'userMoney' => '100元'
);
$UserInfo = new UserInfo;
// 下面需要一步步設置,過程糾結而痛苦
$UserInfo->setUserName($peopleInfo['userName']);
$UserInfo->setUserAge($peopleInfo['userAge']);
$UserInfo->setUserMoney($peopleInfo['userMoney']);
$UserInfo->getPeople();

加上建造者:呼叫端清爽

<?php
include("UserInfo.php");

class UserInfoBuilder {
    protected $obj;

    public function __construct() {
        $this->obj = new UserInfo;
    }

    public function buildPeople($peopleInfo) {
        $this->obj->setUserName($peopleInfo['userName']);
        $this->obj->setUserAge($peopleInfo['userAge']);
        $this->obj->setUserMoney($peopleInfo['userMoney']);
    }

    public function getPeople() {
        $this->obj->getPeople();
    }
}

/* 建立過程被封裝了,使用者只需一行 */
$peopleInfo = array(
    'userName'  => 'initphp',
    'userAge'   => 28,
    'userMoney' => '100元'
);
$UserInfoBuilder = new UserInfoBuilder;
$UserInfoBuilder->buildPeople($peopleInfo);
$UserInfoBuilder->getPeople();

建造者的價值在於:當 UserInfo 日後增加更多必填欄位時,修改集中在 builder 內部,呼叫端不必跟著改。若建立步驟需要更多彈性,也可以把 buildPeople 拆成 buildName()、buildAge() 等鏈式方法,讓呼叫端自行決定組合順序。

參考:《PHP 設計模式》Aaron Saray 著。

Copyright © Linux教程網 All Rights Reserved