面向对象计算器-设计模式简单工厂模式

/**
 * 面向对象计算器
 * 思路:
 * 1、面向对象的基本,封装、继承、多太
 * 2、父类公用类
 * 3、各种运算类
 */

/**
 * 基类,运算类
 * 只提供基本数据,不参与运算
 */

class Operation {
    
    // 第一个数
    public $first_num = 0;
    
    // 第二个数
    public $second_num = 0;
    
    /**
     * 获取结果,其他类覆盖此方法
     * @return double $result
     */
    public function getResult() {
        $result = 0.00;
        
        return $result;
    }
}

/**
 * 加法类
 */
class OperationAdd extends Operation {
    /**
     * 覆盖父类,实现加法算法
     */
    public function getResult() {
        $result = 0;
        return $this->first_num + $this->second_num;
    }
}

/**
 * 减法类
 *
 */
class OperationSub extends Operation {
    /**
     * 覆盖父类,实现加法算法
     */
    public function getResult() {
        $result = 0;
        return $this->first_num - $this->second_num;
    }
}

/**
 * 乘法类
 *
 */
class OperationMul extends Operation {
    /**
     * 覆盖父类,实现加法算法
     */
    public function getResult() {
        $result = 0;
        return $this->first_num * $this->second_num;
    }
}

/**
 * 除类
 *
 */
class OperationDiv extends Operation {
    /**
     * 覆盖父类,实现加法算法
     */
    public function getResult() {
        $result = 0;
        
        if ($this->second_num == 0) {
            throw new  Exception('除法操作第二个参数不能为零!');
            return 0;
        }
        
        return $this->first_num / $this->second_num;
    }
}

/**
 * 工厂类
 */
class OperationFactory {
    /**
     * 工厂函数
     * @param string $operation
     * @return object
     */
    public function createOperation($operation) {
        $oper = null;
        
        switch($operation) {
            case '+':
                $oper = new OperationAdd();
                break;
            case '-':
                $oper = new OperationSub();
                break;
            case '*':
                $oper = new OperationMul();
                break;
            case '/':
                $oper = new OperationDiv();
                break;
            default:
                return 0;
        }
        return $oper;
    }
}


$operation = new OperationFactory();
$oper = $operation->createOperation('/');

$oper->first_num = 10;
$oper->second_num = 20;
var_dump($oper->getResult());

转载于:https://my.oschina.net/wangdk/blog/153459

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值