设计模式 建造者模式

109 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 image.png

介绍

shiyanlou:建造者模式又称为生成器模式,是一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。建造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。

角色

角色说明
Builder抽象构造者类,负责创建一个 Product 对象的各个部件指定抽象接口
ConcreteBuilder具体构造者类,实现 Builder 的接口以构造和装配该产品的各个部件
Director指挥者类,构造一个使用 Builder 接口的对象
Product产品类,表示被构造的复杂对象。ConcreateBuilder 创建该产品的内部表示并定义它的装配过程

角色示例

类名担任角色说明
CoffeeMachineBuilder抽象咖啡机类,阐述制作一杯 Coffee 所需的配料
NespressoConcreteBuilder胶囊咖啡机类,提供 CoffeeMachine 的所需的配料并加以制作
CustomerDirector顾客类,使用 CoffeeMachine 来制作一杯 Coffee
CoffeeProduct咖啡类,使用 Nespresso 来制作一杯 Coffee

UML类图

image.png

代码

<?php 
abstract class CoffeeMachine
{
    protected $coffee;
    abstract public function buildWater();
    abstract public function buildCoffeeBeans();
    abstract public function buildPaperCup();
    abstract public function getResult();
}

class Nespresso extends CoffeeMachine
{
    function __construct()
    {
        $this->coffee = new Coffee();
    }
    public function buildWater(){
        $this->coffee->setWater('水');
    }

    public function buildCoffeeBeans(){
        $this->coffee->setCoffeeBeans('咖啡豆');
    }

    public function buildPaperCup(){
        $this->coffee->setPaperCup('纸杯');
    }

    public function getResult(){
        return $this->coffee;
    }
}

class Coffee
{
    protected $water;
    protected $coffeeBeans;
    protected $paperCup;

    public function setWater($water){
        $this->water = $water;
    }

    public function setCoffeeBeans($coffeeBeans){
        $this->coffeeBeans = $coffeeBeans;
    }

    public function setPaperCup($paperCup){
        $this->paperCup = $paperCup;
    }

    public function show()
    {
        return "这杯咖啡由:".$this->water.'、'.$this->coffeeBeans.'和'.$this->paperCup.'组成';
    }
}

class Customer
{
    public $coffeeMachine;

    public function startCoffeeMachine()
    {
        $this->coffeeMachine->buildWater();
        $this->coffeeMachine->buildCoffeeBeans();
        $this->coffeeMachine->buildPaperCup();
        return $this->coffeeMachine->getResult();
    }

    public function setCoffeeMachine(CoffeeMachine $coffeeMachine)
    {
        $this->coffeeMachine = $coffeeMachine;
    }
}

$nespresso = new Nespresso();
$customer = new Customer();
$customer->setCoffeeMachine($nespresso);
$newCoffee = $customer->startCoffeeMachine();
echo $newCoffee->show();

创建 Nespresso.php,内容如上。

执行

$ php Nespresso.php
这杯咖啡由:水、咖啡豆和纸杯组成