简单工厂模式

1.赋值

abstract class Operation {
    protected $number_a = 0;
    protected $number_b = 0;

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

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

    abstract function result();
}

2.运算

class Add extends Operation{
    public function result()
    {
        return $this->number_a + $this->number_b;
    }
}

class Sub extends Operation{
    public function result()
    {
        return $this->number_a - $this->number_b;
    }
}

class Mul extends Operation{
    public function result()
    {
        return $this->number_a * $this->number_b;
    }
}

3,工厂

class OperationFactory {
    public function createOperate($operate) {
        switch ($operate) {
            case '+':
                $result = new Add();
                break;
            case '-':
                $result = new Sub();
                break;
            case '*':
                $result = new Mul();
                break;
            default:
                throw new \InvalidArgumentException('暂不支持的运算');
        }
        return $result;
    }
}

4,执行


include_once "Operation.php";
include_once "OperationClass.php";
include_once "OperationFactory.php";

class Client
{

    public function test() {
        $oper_obj = new OperationFactory();
        $op = $oper_obj->createOperate('-');
        $op->numberA(1);
        $op->numberB(2);
        $res
            = $op->result();
        echo $res;
    }

}

$Client = new Client();
$Client->test();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值