依赖注入模式

  • 汽车类
class Car
{
    private $engine; // 轮胎

    private $tyre; // 发动机

    private $name; // 品牌

    public function __construct($name, $engine, $tyre)
    {
        $this->name = $name;
        $this->tyre = $tyre;
        $this->engine = $engine;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getTyre()
    {
        return $this->tyre;
    }

    public function getEngine()
    {
        return $this->engine;
    }
}
  • 建造师类
class Builder
{
    private $car;

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

    public function getCarInfo()
    {
        return sprintf('品牌:%s , 发动机:%s , 轮胎:%s',
            $this->car->getName(),
            $this->car->getEngine(),
            $this->car->getTyre());
    }
}
$car = new Car('奔驰','斯特林发动机','米其林轮胎');
$builder = new Builder($car);
echo $builder->getCarInfo(); // 品牌:奔驰 , 发动机:斯特林发动机 , 轮胎:米其林轮胎

你可能感兴趣的:(依赖注入模式)