php工厂模式
2016-07-29
最近在学习设计模式,如下例子,就是简单的工厂模式,初次写,就把代码贴出来分享一下。
class Operation{
    private  $numberA = 0;
    private $numberB = 0;

    public function __get($property_name){
        if(isset($this->$property_name)) {
            return  $this->$property_name;
        }else{
            return(NULL);
        }
    }

    public  function __set($property_name,$value){
        $this->$property_name = $value;
    }
    public function  getResult(){
        $result = 0;
        return $result;
    }

}

/**
 * @todo 加法的操作器
 * Class OperationAdd
 */
class OperationAdd extends Operation {
    public function getResult(){
        $result = 0;
        $getNumberA = $this->numberA;
        $getNumberB = $this->numberB;
        $result = $getNumberB + $getNumberA;
        return $result;
    }
}
/**
 * @todo 减法的操作器
 * Class OperationSub
 */
class OperationSub extends Operation{
    public function getResult(){
        $result = 0;
        $getNumberA = $this->numberA;
        $getNumberB = $this->numberB;
        $result = $getNumberA - $getNumberB;
        return $result;
    }
}

/**
 * @todo 乘法的操作器
 * Class OperationMul
 */
class OperationMul extends Operation{
    public function getResult(){
        $result = 0;
        $getNumberA = $this->numberA;
        $getNumberB = $this->numberB;
        $result = $getNumberA * $getNumberB;
        return $result;
    }
}

/**
 * @todo 除法的操作器
 * Class OperationDiv
 */
class OperationDiv extends Operation{
    public function getResult(){
        $result = 0;
        $getNumberA = $this->numberA;
        $getNumberB = $this->numberB;
        if ('0' == $getNumberB) {
            throw new Exception('除数不能为0',100003);
        }
        $result = $getNumberA/$getNumberB;
        return $result;
    }
}

/**
 * @todo 简单的工厂模式
 * class OperationFactory
 */
class OperationFactory extends Operation{
    public static function createOperation($oper){
        switch ($oper) {
            case '+':
                $myOper = new OperationAdd();
                break;
            case '-':
                $myOper = new OperationSub();
                break;
            case '*':
                $myOper = new OperationMul();
                break;
            case '/':
                $myOper = new OperationDiv();
                break;
            default:
                exit('no oper');
                break;
        }
        return $myOper;
    }
}

//调用方法例子
$oper = OperationFactory::createOperation('+');
$oper->numberA = 1;
$oper->numberB = 2;
$result = $oper->getResult();
echo $result;die;

分享: