设计模式-简单工厂理解

这种模式在我理解,就是通过一个类似路由器的入口,创建属性相同但是操作不同的对象。

最简单的结构:

  1. 一个基础类:可以是普通类,或者抽象类
  2. 不同的操作或行为类:继承上诉基础类
  3. 路由器类:可创建上诉行为类的对象

举个栗子:

a = $a;
    }
    public function setB($b)
    {
        $this->b = $b;
    }
    public function getResult()
    {
        $result = 0;
        return $result;
    }
}
/**
 * Add 
 */
class OperationAdd extends Operation
{
    public function getResult()
    {
        return $this->a + $this->b;
    }
}
/**
 * Mul
 */
class OperationMul extends Operation
{
    public function getResult()
    {
        return $this->a * $this->b;
    } 
}
/**
 * Sub
 */
class OperationSub extends Operation
{
    public function getResult()
    {
        return $this->a - $this->b;
    }
}
/**
 * Div
 */
class OperationDiv extends Operation
{
    public function getResult()
    {
        return $this->a / $this->b;
    }
}
/**
 * Operation Factory
 */
class OperationFactory
{
    public static function createOperation($operation)
    {
        switch ($operation) {
            case '+':
                $oper = new OperationAdd();
                break;
            case '-':
                $oper = new OperationSub();
                break;
            case '/':
                $oper = new OperationDiv();
                break;
            case '*':
                $oper = new OperationMul();
                break;
        }
        return $oper;
    }
}
// 客户端代码
$operation = OperationFactory::createOperation('+');
$operation->setA(1);
$operation->setB(2);
echo $operation->getResult() . PHP_EOL;

你可能感兴趣的:(设计模式-简单工厂理解)