建造者模式

2017-07-12  本文已影响27人  零一间
<?php

/*
 * 建造者模式
 * 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
 */

//汽车类
class Car {
    public $_engine;
    public $_body;
    public $_whell;

    function setEngine($engine) {
        $this->_engine = $engine;
    }

    function setBody($body) {
        $this->_body = $body;
    }

    function setWhellr($whell) {
        $this->_whell = $whell;
    }

    function gerCar() {
        return '引擎:' . $this->_engine . ' 车身:' . $this->_body . ' 轮毂:' . $this->_whell;
    }
}

//抽象建造者
abstract class ACarBuilder {

    public $_car;

    function __construct(Car $car) {
        $this->_car = $car;
    }

    abstract function builderEngine();

    abstract function builderBody();

    abstract function buildeWhellr();

    function getCar() {
        echo '引擎:' . $this->_car->_engine . ' 车身:' . $this->_car->_body . ' 轮毂:' . $this->_car->_whell . "<br>";

    }
}

//巴士建造者
class BusBuilder extends ACarBuilder {

    function builderEngine() {
        $this->_car->setEngine("巴士引擎");
    }

    function builderBody() {
        $this->_car->setBody('巴士车身');
    }

    function buildeWhellr() {
        $this->_car->setWhellr('巴士轮毂');
    }
}

//货车建造者
class TruckBuilder extends ACarBuilder {

    function builderEngine() {
        $this->_car->setEngine("货车引擎");
    }

    function builderBody() {
        $this->_car->setBody('货车车身');
    }

    function buildeWhellr() {
        $this->_car->setWhellr('货车轮毂');
    }

}


//建造指挥者
class Director {
    private $_builder;

    function __construct(ACarBuilder $carBuilder) {
        $this->_builder = $carBuilder;
    }

    function build() {
        $this->_builder->builderEngine();
        $this->_builder->builderBody();
        $this->_builder->buildeWhellr();

    }

    function getCar() {
        $this->_builder->getCar();
    }

}

$bus = new Director(new  BusBuilder(new Car()));
$bus->build();
$bus->getCar();

$bus = new Director(new  TruckBuilder(new Car()));
$bus->build();
$bus->getCar();

/*
引擎:巴士引擎 车身:巴士车身 轮毂:巴士轮毂
引擎:货车引擎 车身:货车车身 轮毂:货车轮毂
*/
上一篇 下一篇

猜你喜欢

热点阅读