行为型设计模式-策略 Strategy

简介

一组实现了同一个策略接口的策略,可以随时指定用哪一种策略完成业务。

策略模式其实跟桥接模式很像,都是通过持有另一个对象,达到组合的效果。

角色

  • Context 上下文

    可设置使用的 Strategy

  • 抽象 Strategy
  • 具体 Strategy

类图

如图,Context使用setStrategy方法设置当前使用的策略,在doSomething中,调用策略的execute方法,实现动态使用策略。

行为型设计模式-策略 Strategy_第1张图片

代码

class Context
{
    private $strategy;

    public function __construct(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function setStrategy(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function doSomeBusinessLogic(): void
    {
        echo "Context: Sorting data using the strategy (not sure how it'll do it)\n";
        $result = $this->strategy->doAlgorithm(["a", "b", "c", "d", "e"]);
        echo implode(",", $result) . "\n";

    }
}

interface Strategy
{
    public function doAlgorithm(array $data): array;
}

class ConcreteStrategyA implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        sort($data);

        return $data;
    }
}

class ConcreteStrategyB implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        rsort($data);

        return $data;
    }
}

$context = new Context(new ConcreteStrategyA());
echo "Client: Strategy is set to normal sorting.\n";
$context->doSomeBusinessLogic();

echo "Client: Strategy is set to reverse sorting.\n";
$context->setStrategy(new ConcreteStrategyB());
$context->doSomeBusinessLogic();

output:

Client: Strategy is set to normal sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
a,b,c,d,e
Client: Strategy is set to reverse sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
e,d,c,b,a

本文由mdnice多平台发布

你可能感兴趣的:(后端)