php,java实现建造者模式

很容易将建造者模式和工厂方法模式混淆,他们的区别是工厂方法模式侧重生产出相同的对象实例,而建造者模式强调的是对同一个对象实例的生产,不同的生产工艺(方法的执行顺序和对属性的赋值)将产生不同效果的对象

类图
这里写图片描述

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值