The builder pattern is primarily designed to eliminate the complexity of other object creation processes.
- There is a user's UserInfo class, create this class, need to create user's name, age, money and other information in order to obtain the user specific information results.
- Create a Userinfobuilder user builder class that encapsulates the UserInfo complex creation of names, ages, and money to simplify the creation of user classes
- Code: UserInfo class, creating a UserInfo class is complex and painful.
//Builder mode, designed to eliminate the complexity of other object creation processes /*describe a user's class, including the user's name, age, and money*/ classUserInfo {protected $userName= ' '; protected $userAge= ' '; protected $userMoney= ' '; Public functionSetusername ($userName) { $this->username =$userName; } Public functionSetuserage ($userAge) { $this->userage =$userAge; } Public functionSetusermoney ($userMoney) { $this->usermoney =$userMoney; } Public functiongetPeople () {Echo"The name of this person is:".$this->setusername. ', Age is: '.$this->userage. ', Money: '.$this-Usermoney; } } /*instantiation, and when creating this user, is very painful, need to set user name, age and Money*/ $peopleInfo=Array( ' UserName ' = ' initphp ', ' userage ', ' usermoney ' = ' 100 ' ); $UserInfo=NewUserInfo; //below need step by step set user information, can get user details, process tangled and painful $UserInfo->setusername ($peopleInfo[' UserName ']); $UserInfo->setuserage ($peopleInfo[' Userage ']); $UserInfo->setusermoney ($peopleInfo[' Usermoney ']); $UserInfo->getpeople ();
Code: Userinfobuilder User Information Builder class that encapsulates the UserInfo creation process and is comfortable for developers to use.
<?PHP//Builder mode, designed to eliminate the complexity of other object creation processes include("userinfo.php"); classUserinfobuilder {protected $obj; Public function__construct () {$this->obj =NewUserInfo; } Public functionBuildpeople ($peopleInfo) { $this->obj->setusername ($peopleInfo[' UserName ']); $this->obj->setuserage ($peopleInfo[' Userage ']); $this->obj->setusermoney ($peopleInfo[' Usermoney ']); } Public functiongetPeople () {$this->obj->getPeople (); } } /*The creation process is encapsulated and the user is simple to use*/ $peopleInfo=Array( ' UserName ' = ' initphp ', ' userage ', ' usermoney ' = ' 100 ' ); $UserInfoBuilder=NewUserinfobuilder; $UserInfoBuilder->buildpeople ($peopleInfo);//Direct a Build $UserInfoBuilder->getpeople ();
Transferred from: http://blog.csdn.net/initphp/article/details/7677561
PHP design Pattern Series-builder mode