简介

一组实现了同一个策略接口的策略,能够随时指定用哪一种策略实现业务。

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

角色

  • Context 上下文

    可设置应用的 Strategy

  • 形象 Strategy
  • 具体 Strategy

类图

如图,Context应用setStrategy办法设置以后应用的策略,在doSomething中,调用策略的execute办法,实现动静应用策略。

代码

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,eClient: 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多平台公布