简单工厂【Simple Factory】

实例

// 操作类
abstract class Operation
{
    protected $a = 0;
    protected $b = 0;

    public function setA($a)
    {
        $this->a = $a;
    }

    public function setB($b)
    {
        $this->b = $b;
    }

    abstract protected function getResult();
}

// 加
class Add extends Operation
{
    public function getResult()
    {
        return $this->a + $this->b;
    }
}

// 减
class Sub extends Operation
{
    public function getResult()
    {
        return $this->a - $this->b;
    }
}

// 乘
class Mul extends Operation
{
    public function getResult()
    {
        return $this->a * $this->b;
    }
}

// 除
class Div extends Operation
{
    public function getResult()
    {
        return $this->a / $this->b;
    }
}

// 操作工厂类
class OperationFactory
{
    public static function createOperation($args)
    {
        switch ($args) {
            case '+':
                $operation = new Add();
                break;
            case '-':
                $operation = new Sub();
                break;
            case '*':
                $operation = new Mul();
                break;
            case '/':
                $operation = new Div();
                break;
        }

        return $operation;
    }
}

$operation = OperationFactory::createOperation('+');
$operation->setA(1);
$operation->setB(2);
echo $operation->getResult() . PHP_EOL; // 3
interface ProductInterface
{
    public function showProductInfo();
}

class ProductA implements ProductInterface
{
    public function showProductInfo()
    {
        echo 'This is product A', PHP_EOL;
    }
}

class ProductB implements ProductInterface
{
    public function showProductInfo()
    {
        echo 'This is product B', PHP_EOL;
    }
}

class ProductFactory
{
    public static function factory($ProductType)
    {
        $ProductType = 'Product' . strtoupper($ProductType);
        if (class_exists($ProductType)) {
            return new $ProductType();
        } else {
            throw new Exception("Error Processing Request", 1);
        }
    }
}

// 这里需要一个产品型号为 A 的对象
try {
    $x = ProductFactory::factory('A'); // This is product A
} catch (Exception $e) {
}
$x->showProductInfo(); // This is product A

// 这里需要一个产品型号为 B 的对象
try {
    $o = ProductFactory::factory('B'); // This is product B
} catch (Exception $e) {
}
$o->showProductInfo(); // This is product B

核心方法论

设计目标

复用原则

示例中的模式

两个示例均体现了简单工厂模式 (Simple Factory)

  1. 第一个示例 (OperationFactory): 通过 switch 语句集中创建不同的运算对象,将对象的实例化和客户端使用分离开来。
  2. 第二个示例 (ProductFactory): 利用反射/动态类名(class_existsnew $ProductType())来创建不同的产品对象,进一步降低了工厂内的逻辑判断复杂度。