Linux教程網
建造者模式主要是為了消除其它對象復雜的創建過程。
-
有一個用戶的UserInfo類,創建這個類,需要創建用戶的姓名,年齡,金錢等信息,才能獲得用戶具體的信息結果。
-
創建一個UserInfoBuilder 用戶建造者類,這個類,將UserInfo復雜的創建姓名,年齡,金錢等操作封裝起來,簡化用戶類的創建過程
- 代碼:UserInfo類,創建UserInfo類是復雜的,痛苦的。
- //建造者模式,目的是消除其它對象復雜的創建過程
-
- /* 描述一個用戶的類,包含用戶姓名,年齡,金錢 */
- 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->setUserName . ',年齡是:' . $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();
- 代碼:UserInfoBuilder 用戶信息建造者類,將UserInfo的創建過程封裝掉,開發者使用起來心情舒暢
- <?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); //直接一個build
- $UserInfoBuilder->getPeople();
參考:《PHP設計模式》Aaron Saray著
Copyright ©
Linux教程網 All Rights Reserved