策略模式:指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。这么说或许有点抽象, 设想有这么一种场景。 我们写了一个博客网站,为了能够方便的更换外观, 我们指定了一个theme参数, 并且在渲染的函数中进行了一系列的if/else判断(或者swith), 这样出现了什么问题呢, 每次我们尝试增加一种主题, 都不可避免的要修改render函数。这样显然不利于维护, 策略模式是通过注入不同的算法,来实现自动切换, 避免了不必要的if/else和对应用策略类的修改。
    strategy-1.png

    1. <?php
    2. /**
    3. * Created by PhpStorm.
    4. * User: raye
    5. * Date: 2018/3/20
    6. * Time: 9:40
    7. */
    8. /**
    9. * 定义一个规范, 所有的主题都应该实现render方法
    10. * Interface IThemeStrategy
    11. */
    12. interface IThemeStrategy{
    13. public function render($view);
    14. }
    15. class GeneralTheme implements IThemeStrategy {
    16. public function render($view)
    17. {
    18. echo 'apply general theme successful.' . PHP_EOL;
    19. }
    20. }
    21. class SimpleTheme implements IThemeStrategy{
    22. public function render($view)
    23. {
    24. echo 'apply simple theme successful.' . PHP_EOL;
    25. }
    26. }
    27. /**
    28. * 通过使用构造函数注入不同的主题策略,当然也可以使用setter方式
    29. * Class Blog
    30. */
    31. class Blog
    32. {
    33. private $renderHandler;
    34. /**
    35. * Blog constructor.
    36. * @param IThemeStrategy $renderHandler 约束类的行为
    37. */
    38. public function __construct(IThemeStrategy $renderHandler)
    39. {
    40. $this->renderHandler = $renderHandler;
    41. }
    42. public function render($content){
    43. $this->renderHandler->render($content);
    44. }
    45. }
    46. $blog = new Blog(new GeneralTheme());
    47. $blog->render('');
    48. $blog = new Blog(new SimpleTheme());
    49. $blog->render('');

    策略模式的优点:

    1. 减少了if/else, 这是最直观的了
    2. 便于扩展, 增加新主题的时候, 不必修改blog的render方法,就可以完成扩展
    3. 便于维护, 和上一条的理由一致.