What is builder mode?
The builder mode is mainly used to eliminate complicated creation processes of other objects.
Design scenario
There is a user's UserInfo class. To create this class, you must create the user's name, age, money, and other information to obtain the user's specific information results.
Creates a UserInfoBuilder user builder class. This class encapsulates complex UserInfo creation operations, such as name, age, and money, to simplify the creation process of user classes.
Code: UserInfo class. It is complicated and painful to create a UserInfo class.
[Php] view plaincopyprint?
// Builder mode, designed to eliminate complicated creation processes of other objects
/* Describes a user's class, including the user name, age, and money */
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 "the name of this person is :". $ this-> setUserName. ', age :'. $ this-> userAge. ', money :'. $ this-> userMoney;
}
}
/* It is very painful to instantiate and create this user. You need to set the user name, age, and money */
$ PeopleInfo = array (
'Username' => 'initphp ',
'Userage' => 28,
'Usermoney' => '000000'
);
$ UserInfo = new UserInfo;
// The following step-by-step setting of user information is required to obtain detailed user information.
$ UserInfo-> setUserName ($ peopleInfo ['username']);
$ UserInfo-> setUserAge ($ peopleInfo ['userage']);
$ UserInfo-> setUserMoney ($ peopleInfo ['usermoney']);
$ UserInfo-> getPeople ();
Code: UserInfoBuilder user information builder class, which encapsulates the UserInfo creation process and allows developers to use it easily.
[Php]
<? Php
// Builder mode, designed to eliminate complicated creation processes of other objects
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 ();
}
}
/* The creation process is encapsulated, which is easy to use */
$ PeopleInfo = array (
'Username' => 'initphp ',
'Userage' => 28,
'Usermoney' => '000000'
);
$ UserInfoBuilder = new UserInfoBuilder;
$ UserInfoBuilder-> buildPeople ($ peopleInfo); // directly build
$ UserInfoBuilder-> getPeople ();
Author: initphp