工厂方法模式

  • 没有做反射类检测

<?php
/**
 * 工厂方法模式: 定义用于创建对象的接口,让子类决定实例化哪一个类。
 * 工厂方法是一个类的实例化延迟到子类。
 */

// ********** 操作类 ********** //
abstract class Operation
{
    protected $_num1;
    protected $_num2;
    public function __get($name)
    {
        return $this->$name;
    }
    public function __set($name, $value)
    {
        $this->$name = $value;
    }
    public function getResult()
    {
        return 0;
    }
}
class OperationAdd extends Operation
{
    public function getResult()
    {
        return $this->_num1 + $this->_num2;
    }    
}
class OperationSub extends Operation
{
    public function getResult()
    {
        return $this->_num1 - $this->_num2;
    }
}
class OperationMul extends Operation
{
    public function getResult()
    {
        return $this->_num1 * $this->_num2;
    }
}
class OperationDiv extends Operation
{
    public function getResult()
    {
        if (empty($this->_num2)) {
            throw new Exception("除数不能为0", 1);
            
        }
        return $this->_num1 / $this->_num2;
    }
}

// ********** 工厂接口 - 类 ********** //
Interface IFactory
{
    public function CreateOperation();
}
class AddFacroty implements IFactory
{
    public function CreateOperation()
    {
        return new OperationAdd();
    }
}
class SubFactory implements IFactory
{
    public function CreateOperation()
    {
        return new OperationSub();
    }
}
class MulFactory implements IFactory
{
    public function CreateOperation()
    {
        return new OperationMul();
    }
}
class DivFactory implements IFactory
{
    public function CreateOperation()
    {
        return new OperationDiv();
    }
}

// client
try {
    //工厂方法
    $f = new AddFacroty();
    $o = $f->CreateOperation();

    $o->_num1 = 10;
    $o->_num2 = 2;
    print_r($o->getResult());
} catch (Exception $e) {
    echo $e->getMessage();
}

蛇叔编程心法
16 声望1 粉丝

爱生活,爱学习,爱工作,足够拼命,足够努力。


« 上一篇
装饰器模式
下一篇 »
原型模式