PHP经验分享

PHP设计模式-策略模式

2018-12-07  本文已影响7人  PHP的艺术编程

策略模式

用途

分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)。

例子

代码

namespace Strategy;


interface MathStrategy
{
    public function calc(int $num1, int $num2);
}
namespace Strategy;


class MathAdd implements MathStrategy
{
    public function calc(int $num1, int $num2): int
    {
        return $num1 + $num2;
    }
}
namespace Strategy;


class MathSub implements MathStrategy
{
    public function calc(int $num1, int $num2): int
    {
        return $num1 - $num2;
    }
}
namespace Strategy;


class Computer
{
    public $math_class;

    public function __construct(int $type)
    {
        if ($type == 1) {
            $this->math_class = new MathAdd();
        } elseif ($type == 2) {
            $this->math_class = new MathSub();
        }
    }

    /**
     * 返回结构
     * @param int $num1
     * @param int $num2
     * @return int
     */
    public function getResult(int $num1, int $num2): int
    {
        if ($this->math_class === null) echo '对象为空';
        return $this->math_class->calc($num1, $num2);
    }
}
<?php


// 注册自加载
use Strategy\Computer;

spl_autoload_register(function ($class) {
    require dirname($_SERVER['SCRIPT_FILENAME']) . '//..//' . str_replace('\\', '/', $class) . '.php';
});

$class = new Computer(1);
echo $class->getResult(1,4);

echo '<br>';

$class2 = new Computer(2);
echo $class2->getResult(2, 6);

总结

上一篇 下一篇

猜你喜欢

热点阅读