工厂方法模式
没有做反射类检测
<?php
/**
* 工厂方法模式: 定义用于创建对象的接口,让子类决定实例化哪一个类。
* 工厂方法是一个类的实例化延迟到子类。
*/
// ********** 操作类 ********** //
abstract class Operation
{
protected $_num1;
protected $_num2;
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
}
public function getResult()
{
return 0;
}
}
class OperationAdd extends Operation
{
public function getResult()
{
return $this->_num1 + $this->_num2;
}
}
class OperationSub extends Operation
{
public function getResult()
{
return $this->_num1 - $this->_num2;
}
}
class OperationMul extends Operation
{
public function getResult()
{
return $this->_num1 * $this->_num2;
}
}
class OperationDiv extends Operation
{
public function getResult()
{
if (empty($this->_num2)) {
throw new Exception("除数不能为0", 1);
}
return $this->_num1 / $this->_num2;
}
}
// ********** 工厂接口 - 类 ********** //
Interface IFactory
{
public function CreateOperation();
}
class AddFacroty implements IFactory
{
public function CreateOperation()
{
return new OperationAdd();
}
}
class SubFactory implements IFactory
{
public function CreateOperation()
{
return new OperationSub();
}
}
class MulFactory implements IFactory
{
public function CreateOperation()
{
return new OperationMul();
}
}
class DivFactory implements IFactory
{
public function CreateOperation()
{
return new OperationDiv();
}
}
// client
try {
//工厂方法
$f = new AddFacroty();
$o = $f->CreateOperation();
$o->_num1 = 10;
$o->_num2 = 2;
print_r($o->getResult());
} catch (Exception $e) {
echo $e->getMessage();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。