# 简单工厂模式

### 普通初学者喜欢的写法

#### 例子：实现一个简单计算器

``````
class Program
{
public \$symbol;
public \$num1;
public \$num2;

public function __construct(\$symbol, \$num1, \$num2)
{
\$this->symbol = \$symbol;
\$this->num1 = \$num1;
\$this->num2 = \$num2;
}

public function calculate()
{
switch (\$this->symbol) {
case '+':
\$result = \$this->num1 + \$this->num2;
break;
case '-':
\$result = \$this->num1 - \$this->num2;
break;
case '*':
\$result = \$this->num1 * \$this->num2;
break;
case '/':
if (\$this->num2 != 0) {
\$result = \$this->num1 / \$this->num2;
} else {
\$result = "除数不能为0";
}
break;
default:
\$result = "运算符错误";
}

return \$result;
}
}

\$program = new Program('+', 1, 14);
\$result = \$program->calculate();
print_r(\$result);//15
``````

### 使用简单工厂模式重新实现达到解耦的目的

``````
class Operation
{
public \$num1;
public \$num2;
}

{
public function getResult()
{
\$result = \$this->num1 + \$this->num2;
return \$result;
}
}

class OperationSub extends Operation
{
public function getResult()
{
\$result = \$this->num1 - \$this->num2;
return \$result;
}
}

class OperationMul extends Operation
{
public function getResult()
{
\$result = \$this->num1 * \$this->num2;
return \$result;
}
}

class OperationDiv extends Operation
{
public function getResult()
{

if (\$this->num2 != 0) {
\$result = \$this->num1 / \$this->num2;
} else {
\$result = "除数不能为0";
}
return \$result;
}
}

class OperationFactory
{
public static function createOperate(\$symbol)
{
switch (\$symbol) {//多态
case '+':
break;
case '-':
\$result = new OperationSub();
break;
case '*':
\$result = new OperationMul();
break;
case '/':
\$result = new OperationDiv();
break;
default:
\$result = NULL;
}
return \$result;
}
}

\$operationFactory = OperationFactory::createOperate('+');
\$operationFactory->num1 = 21;
\$operationFactory->num2 = 11;

echo \$operationFactory->getResult();//32``````

(=￣ω￣=)··· 暂无内容！

6

2

22

17