文中对于建造者设计模式的说明让人很难理解

我在《PHP设计模式》看到一段对于建造者设计模式的说明,可能比较容易理解:

建造者设计模式定义了处理其他对象的复杂构建的对象设计。

建造者设计模式的目的是消除其他对象的复杂创建过程。使用建造者设计模式不仅是最佳做法,而且在某个对象的构造和配置方法改变时可以尽可能的较少重复更改代码。

大致流程如下:

namespace DesignPatterns\Creational\Builder;

interface Product
{
    public function setPrice($price);

    public function setBrand($brand);

    public function setName($name);

    public function getAttributes() :array ;
}
class BikeProduct implements Product
{
    protected $attributes = [];

    public function __construct()
    {
        $this->attributes['type'] = 'Bike';
    }

    public function setBrand($brand)
    {
        $this->attributes['brand'] = $brand;
    }

    public function setName($name)
    {
        $this->attributes['name'] = $name;
    }

    public function setPrice($price)
    {
        $this->attributes['price'] = $price;
    }

    public function getAttributes(): array
    {
        return $this->attributes;
    }
}
namespace DesignPatterns\Creational\Builder;

interface Builder
{
    public function build() :void ;
}
namespace DesignPatterns\Creational\Builder;

class BikeProductBuilder implements Builder
{
    protected $options;

    protected $product;

    public function __construct(array $options)
    {
        $this->product = new BikeProduct();

        $this->options = $options;
    }

    public function build() :void
    {
        $this->product->setBrand($this->options['brand']);

        $this->product->setName($this->options['name']);

        $this->product->setPrice($this->options['price']);
    }

    public function getProduct() :Product
    {
        return $this->product;
    }
}

namespace DesignPatterns\Creational\Builder;

use PHPUnit\Framework\TestCase;

class BuilderTest extends TestCase
{
    public function testBikeInstance()
    {
        $builder = new BikeProductBuilder([
            'brand' => 'Giant',
            'name' => 'ATX720',
            'price' => 2280
        ]);

        $builder->build();

        $this->assertInstanceOf(BikeProduct::class, $builder->getProduct());
    }

    public function testBikeAttributes()
    {
        $builder = new BikeProductBuilder([
            'brand' => 'Mrida',
            'name' => 'XiongShi750',
            'price' => 2298
        ]);

        $builder->build();

        $attributes = $builder->getProduct()->getAttributes();

        $this->assertSame(2298, $attributes['price']);
    }
}

UML图就不画了,大致就是这样子吧。顺便加入了“工厂方法模式”,就是其中的 Builder 和 BikeProductBuilder 。感觉这个“工厂方法模式”更能够体现面向对象的开闭原则。

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!