1

简单工厂模式

  • 书写计算器小程序

  • 实现简单工厂模式

<?php
/**
 * 简单工厂模式 - 计算器
 */

// 公共需要继承的类
class Operation
{
    private $ref = null;
    protected $_num1;
    protected $_num2;

    public function __construct()
    {
        $this->ref = new ReflectionObject($this);
    }
    public function __set($name, $value)
    {
        if ($this->ref->hasProperty("$name")) {
            $this->$name = $value;
        }
    }
    public function __get($name)
    {    
        if ($this->ref->hasProperty("$name")) {
            return $this->$name;
        }
    }
    public function getResutl()
    {
        return 0;
    }
}

// 四则运算的子类
class Add extends Operation
{
    public function getResutl()
    {
        return $this->_num1 + $this->_num2;
    }
}

class Sub extends Operation
{
    public function getResutl()
    {
        return $this->_num1 - $this->_num2;
    }
}

class Mul extends Operation
{
    public function getResutl()
    {
        return $this->_num1  * $this->_num2;
    }
}

class Div extends Operation
{
    public function getResutl()
    {
        if (empty($this->_num2)) {
            throw new Exception("除数不能为0\n");
        }
        return $this->_num1 / $this->_num2;
    }
}


class OperationFactory
{
    public static function createOperate($oper)
    {
        $res = null;
        switch ($oper) {
            case '+':
                $res = new Add();
                break;
            case '-':
                $res = new Sub();
                break;
            case '*': 
                $res = new Mul();
                break;
            case '/':
                $res = new Div();
                break;
            default:
                throw new Exception("Operation 错误\n", 1);
                break;
        }
        return $res;
    }
}

/*// 主程序
try {
    // 单独实例化,需要
    // 公共示例化-> 简单工厂模式
    $a = new Div();
    $a->_num1 = 11;
    $a->_num2 = 0;
    var_dump($a->getResutl());

} catch (Exception $e) {
    echo $e->getMessage();
}*/

// 使用简单工厂模式
try {

    $oper = OperationFactory::createOperate('+');
    $oper->_num1 = 11;
    $oper->_num2 = 2;
    echo $oper->getResutl();
} catch (Exception $e) {
    echo $e->getMessage();
}

/**
 * think: java 是强类型语言,父类的引用指向子类的实例
 * 而php不是
 */

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

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


下一篇 »
策略模式