很容易将建造者模式和工厂方法模式混淆,他们的区别是工厂方法模式侧重生产出相同的对象实例,而建造者模式强调的是对同一个对象实例的生产,不同的生产工艺(方法的执行顺序和对属性的赋值)将产生不同效果的对象
类图
java实现
产品类
public class Product {
public void setPart1(){
}
public void setPart2(){
}
}
建造者抽象类
public abstract class AbsBuilder {
public abstract Product getProduct();
public abstract void setProductPart();
}
建造者实现类
public class Product1Builder extends AbsBuilder {
private Product mProduct = new Product();
@Override
public Product getProduct() {
return this.mProduct;
}
@Override
public void setProductPart() {
this.mProduct.setPart1();
this.mProduct.setPart2();
}
}
public class Product3Builder extends AbsBuilder {
private Product mProduct = new Product();
@Override
public Product getProduct() {
return this.mProduct;
}
@Override
public void setProductPart() {
this.mProduct.setPart2();
}
}
场景类
public class Client {
public Product getProduct1(){
AbsBuilder builder = new Product1Builder();
builder.setProductPart();
return builder.getProduct();
}
public Product getProduct3(){
AbsBuilder builder = new Product3Builder();
builder.setProductPart();
return builder.getProduct();
}
}
php实现
class Product
{
public function setPart1()
{
echo 'setPart1';
}
public function setPart2()
{
echo 'setPart2';
}
}
abstract class AbsBuilder
{
public abstract function getProduct();
public abstract function setProductPart();
}
class Product1Builder extends AbsBuilder
{
public $product;
public function __construct()
{
$this->product = new Product;
}
public function getProduct()
{
return $this->product;
}
public function setProductPart()
{
$this->product->setPart1();
$this->product->setPart2();
}
}
class Product2Builder extends AbsBuilder
{
public $product;
public function __construct()
{
$this->product = new Product;
}
public function getProduct()
{
return $this->product;
}
public function setProductPart()
{
$this->product->setPart1();
}
}
class Client
{
public function getProduct1()
{
$builder = new Product1Builder;
$builder->setProductPart();
return $builder->getProduct();
}
public function getProduct3()
{
$builder = new Product2Builder;
$builder->setProductPart();
return $builder->getProduct();
}
}
$client = new Client;
$client->getProduct1();
$client->getProduct3();