设计模式-工厂方式

<?php 
/**
 * 简单工厂模式
 * 简单工厂模式的最大有点在于工厂类中包含了必要的逻辑
 * 根据客户端的选择条件动态实例化相关的类
 * 对于客户端来说,去除了与具体产品的依赖
 */

/**
 * 抽象运算符
 * @author wangdk
 */
abstract class Operation
{
    public $numA;
    public $numB;
    
    public function __construct($numA, $numB) {
        $this->numA = $numA;
        $this->numB = $numB;
    }
    
    abstract public function GetResult();
}


/**
 * 具体运算符
 * @author wangdk
 *
 */
class DivOperation extends Operation
{
    public function GetResult()
    {
        return $this->numA / $this->numB;
    }
}

/**
 * 运算符工厂对象
 */

interface Factory
{
    public function CreateOperation($a, $b);
}

class DivFactory
{
    public function CreateOperation($a, $b)
    {
        return new DivOperation($a, $b);
    }
}

$div = new DivFactory();
$divOperation = $div->CreateOperation(2, 3);
echo $divOperation->GetResult();
?>

你可能感兴趣的:(设计模式-工厂方式)