PHP实现简单工厂模式

PHP代码实现简单工厂模式

<?php

// 简单工厂模式

abstract class Operation
{
	public $numberA = 0;

	public $numberB = 0;

	abstract public function getResult();
}

// 加法运算
class OperationAdd extends Operation
{
	public function getResult()
	{
		return $this->numberA + $this->numberB;
	}
}

// 减法运算
class OperationSub extends Operation
{
	public function getResult()
	{
		return $this->numberA - $this->numberB;
	}
}

// 乘法运算
class OperationMult extends Operation
{
	public function getResult()
	{
		return $this->numberA * $this->numberB;
	}
}

// 除法运算
class OperationDiv extends Operation
{
	public function getResult()
	{
		return $this->numberA / $this->numberB;
	}
}

// 运算工厂类
class OperationFactory
{
	public function createOperation($option)
	{
		switch ($option) {
			case '+':
				$result = new OperationAdd();
				break;
			case '-':
				$result = new OperationSub();
				break;
			case '*':
				$result = new OperationMult();
				break;
			case '/':
				$result = new OperationDiv();
				break;
		}

		return $result;
	}
}


$operationObject = (new OperationFactory())->createOperation('+');
$operationObject->numberA = 3;
$operationObject->numberB = 5;

var_dump($operationObject->getResult());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值