[关闭]
@Chiang 2020-01-03T11:11:34.000000Z 字数 1415 阅读 524

行为型--模板方法模式

设计模式


  • 抽象类
  • 具体类

模板方法模式

抽象类

  1. <?php
  2. /**
  3. * AbstractClass.php
  4. *
  5. * @author Luffy <lufei@swoole.com>
  6. * @date 2019/12/24
  7. * @copyright Swoole, Inc.
  8. * @package sy-records/design-patterns
  9. */
  10. namespace Luffy\DesignPatterns\TemplateMethod;
  11. abstract class AbstractClass
  12. {
  13. final public function templateMethod()
  14. {
  15. $this->open();
  16. $this->startPlay();
  17. $this->endPlay();
  18. }
  19. protected function open()
  20. {
  21. echo "open game\n";
  22. }
  23. abstract protected function startPlay();
  24. protected function endPlay()
  25. {
  26. echo "end game\n";
  27. }
  28. }

具体类

  1. <?php
  2. /**
  3. * ConcreteClass1.php
  4. *
  5. * @author Luffy <lufei@swoole.com>
  6. * @date 2019/12/24
  7. * @copyright Swoole, Inc.
  8. * @package sy-records/design-patterns
  9. */
  10. namespace Luffy\DesignPatterns\TemplateMethod;
  11. class ConcreteClass1 extends AbstractClass
  12. {
  13. protected function startPlay()
  14. {
  15. echo "start play CF\n";
  16. }
  17. }
  1. <?php
  2. /**
  3. * ConcreteClass2.php
  4. *
  5. * @author Luffy <lufei@swoole.com>
  6. * @date 2019/12/24
  7. * @copyright Swoole, Inc.
  8. * @package sy-records/design-patterns
  9. */
  10. namespace Luffy\DesignPatterns\TemplateMethod;
  11. class ConcreteClass2 extends AbstractClass
  12. {
  13. protected function startPlay()
  14. {
  15. echo "start play LOL\n";
  16. }
  17. }

客户端调用

  1. <?php
  2. /**
  3. * Client.php
  4. *
  5. * @author Luffy <lufei@swoole.com>
  6. * @date 2019/12/24
  7. * @copyright Swoole, Inc.
  8. * @package sy-records/design-patterns
  9. */
  10. namespace Luffy\DesignPatterns\TemplateMethod;
  11. require __DIR__ . "/../vendor/autoload.php";
  12. class Client
  13. {
  14. public static function run()
  15. {
  16. $obj1 = new ConcreteClass1();
  17. $obj1->templateMethod();
  18. echo "===========\n";
  19. $obj2 = new ConcreteClass2();
  20. $obj2->templateMethod();
  21. }
  22. }
  23. Client::run();

参考资料:
swoole微课堂
示例代码

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注