我创建了一个名为Calculator的类,它带有加,减,乘和除功能.计算器仅限于添加两个数字并返回结果.
我对OOP比较陌生,想在课堂上得到一些输入,我是否采取了漫长的路线,如果我做的是有另一种简化课程的方法.
我对OOP比较陌生,想在课堂上得到一些输入,我是否采取了漫长的路线,如果我做的是有另一种简化课程的方法.
这是代码:
- class Calculator {
- private $_val1,$_val2;
- public function __construct($val1,$val2){
- $this->_val1 = $val1;
- $this->_val2 = $val2;
- }
- public function add(){
- return $this->_val1 + $this->_val2;
- }
- public function subtract(){
- return $this->_val1 - $this->_val2;
- }
- public function multiply (){
- return $this->_val1 * $this->_val2;
- }
- public function divide () {
- return $this->_val1 / $this->_val2;
- }
- }
- $calc = new Calculator(3,4);
- echo "<p>3 + 4 = ".$calc->add(). "</p>";
- $calc = new Calculator (15,12);
- echo "<p>15 - 12 = ".$calc->subtract(). "</p>";
- $calc = new Calculator (20,2);
- echo "<p> 20 * 2 = ".$calc->multiply(). "</p>";
- $calc = new Calculator (20,2);
- echo "<p> 20 / 2 = ".$calc ->divide(). "</p>";
恕我直言,你应该使用多态性.
This Video可以帮助您理解这一原则
This Video可以帮助您理解这一原则
这是我的思维方式.
首先,为您需要的任何操作定义接口
- interface OperationInterface
- {
- public function evaluate(array $operands = array());
- }
然后,创建计算器支架
- class Calculator
- {
- protected $operands = array();
- public function setOperands(array $operands = array())
- {
- $this->operands = $operands;
- }
- public function addOperand($operand)
- {
- $this->operands[] = $operand;
- }
- /**
- * You need any operation that implement the given interface
- */
- public function setOperation(OperationInterface $operation)
- {
- $this->operation = $operation;
- }
- public function process()
- {
- return $this->operation->evaluate($this->operands);
- }
- }
然后,您可以定义操作,例如,添加
- class Addition implements OperationInterface
- {
- public function evaluate(array $operands = array())
- {
- return array_sum($operands);
- }
- }
你会像以下一样使用它:
- $calculator = new Calculator;
- $calculator->setOperands(array(4,2));
- $calculator->setOperation(new Addition);
- echo $calculator->process(); // 6
有了这一点,如果要添加任何新行为或修改现有行为,只需创建或编辑一个类.
例如,假设您需要模数运算
- class Modulus implements OperationInterface
- {
- public function evaluate(array $operands = array())
- {
- $equals = array_shift($operands);
- foreach ($operands as $value) {
- $equals = $equals % $value;
- }
- return $equals;
- }
- }
然后,
- $calculator = new Calculator;
- $calculator->setOperands(array(4,2));
- $calculator->setOperation(new Addition); // 4 + 2
- echo $calculator->process(); // 6
- $calculator->setOperation(new Modulus); // 4 % 2
- echo $calculator->process(); // 0
- $calculator->setOperands(array(55,10)); // 55 % 10
- echo $calculator->process(); // 5
如果您计划重用此代码或将其作为库提供,则用户不会修改您的源代码.
但是,如果他想要一个未定义的Substraction或BackwardSubstraction方法呢?
他只需要在他的项目中创建自己的Substraction类,它实现OperationInterface以便与你的库一起工作.
它更容易阅读
在查看项目架构时,更容易看到这样的文件夹
并立即知道哪个文件包含所需的行为.