PHP design pattern Builder pattern belongs to creation pattern
Overview: separates the construction of a complex object from its representation so that different representations can be created during the same construction process.
Advantages:
The builder mode can well separate the implementation of an object from the related 'business' logic, so that the event logic can be increased (or changed) without changing the event logic) easy to implement
Disadvantages:
Modifications to the builder interface will cause modifications to all execution classes.
The builder should be used in the following situations:
1. The product object to be generated has a complex internal structure
2. the properties of the product objects to be generated depend on each other. The Builder mode can force the order of generation.
3. some other objects in the system will be used during object creation. these objects are not easy to obtain during product creation.
The builder mode has the following benefits:
1. the builder mode allows the internal representation of the product to change independently. The Builder mode allows the client to know the details of the product's internal composition.
2. Each Builder is relatively independent of other builders.
3. the final products built by the model are easier to control
Class Product {
Public $ type = null;
Public $ price = null;
Public $ color = null;
Public function setType ($ type ){
$ This-> type = $ type;
}
Public function setPrice ($ price ){
$ This-> price = $ price;
}
Public function setColor ($ color ){
$ This-> color = $ color;
}
}
$ Config = array (
'Type' => 'shirt ',
'Price' => 100,
'Color' => 'red ',
);
// Do not use the builder mode
$ Product = new Product ();
$ Product-> setType ($ config ['type']);
$ Product-> setPrice ($ config ['price']);
$ Product-> setColor ($ config ['color']);
Builder mode
/* Builder class */
Class ProductBuilder {
Public $ config = null;
Public $ object = null;
Public function _ construct ($ config ){
$ This-> object = new Product ();
$ This-> config = $ config;
}
Public function build (){
$ This-> object-> setType ($ this-> config ['type']);
$ This-> object-> setPrice ($ this-> config ['price']);
$ This-> object-> setColor ($ this-> config ['color']);
}
Public fuction getProduct (){
Return $ this-> object;
}
}
$ ObjBuilder = new ProductBuilder ($ config );
$ ObjBuilder-> build ();
$ ObjProduct = $ objBuilder-> getProduct ();
Var_dump ($ objProduct );