2020-06-30 抽象工厂

2020-06-30  本文已影响0人  布衣码农

抽象工厂


特点

抽象工厂比工厂模式多了更多的维度大体相同, 但当需要添加一个维度的时候,所有工厂类都需要去实现它

角色

  1. 抽象工厂

  2. 具体工厂

  3. 抽象产品

  4. 具体产品

UML图

image.png

代码演示

<?php


interface Farm
{
    public function animal(): Animal;

    public function plant(): Plant;
}

interface Plant
{
    public function show();
}

interface Animal
{
    public function show();
}

/**
 * 北京农场主要生产牛与水果
 * Class BjFarm
 */
class BjFarm implements Farm
{
    public function __construct()
    {
        echo "北京农场:" . PHP_EOL;
    }

    public function animal(): Animal
    {
        return new Cattle();
    }

    public function plant(): Plant
    {
        return new Fruits();
    }
}

/**
 * 天津工厂 主要生产 羊跟蔬菜
 * Class TjFarm
 */
class TjFarm implements Farm
{
    public function __construct()
    {
        echo "天津农场:" . PHP_EOL;
    }

    public function animal(): Animal
    {
        return new Sheep();
    }

    public function plant(): Plant
    {
        return new Vegetables();
    }
}

/**
 * 蔬菜类
 * Class Vegetables
 */
class Vegetables implements Plant
{
    public function show()
    {
        echo "\t生产了很多蔬菜" . PHP_EOL;
    }
}

/**
 * 羊类
 * Class Sheep
 */
class Sheep implements Animal
{
    public function show()
    {
        echo "\t生产了很多羊" . PHP_EOL;
    }
}

/**
 * 水果类
 * Class Fruits
 */
class Fruits implements Plant
{
    public function show()
    {
        echo "\t生产了很多水果" . PHP_EOL;
    }
}

/**
 * 牛类
 * Class Cattle
 */
class Cattle implements Animal
{
    public function show()
    {
        echo "\t生产了很多牛" . PHP_EOL;
    }
}


class App
{
    public static function run(Farm $farm)
    {
        $farm->animal()->show();
        $farm->plant()->show();
    }
}

App::run(new BjFarm());
App::run(new TjFarm());
上一篇 下一篇

猜你喜欢

热点阅读