@Chiang
2020-01-03T11:11:34.000000Z
字数 1415
阅读 520
设计模式
- 抽象类
- 具体类
<?php
/**
* AbstractClass.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/24
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\TemplateMethod;
abstract class AbstractClass
{
final public function templateMethod()
{
$this->open();
$this->startPlay();
$this->endPlay();
}
protected function open()
{
echo "open game\n";
}
abstract protected function startPlay();
protected function endPlay()
{
echo "end game\n";
}
}
<?php
/**
* ConcreteClass1.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/24
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\TemplateMethod;
class ConcreteClass1 extends AbstractClass
{
protected function startPlay()
{
echo "start play CF\n";
}
}
<?php
/**
* ConcreteClass2.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/24
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\TemplateMethod;
class ConcreteClass2 extends AbstractClass
{
protected function startPlay()
{
echo "start play LOL\n";
}
}
<?php
/**
* Client.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/24
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\TemplateMethod;
require __DIR__ . "/../vendor/autoload.php";
class Client
{
public static function run()
{
$obj1 = new ConcreteClass1();
$obj1->templateMethod();
echo "===========\n";
$obj2 = new ConcreteClass2();
$obj2->templateMethod();
}
}
Client::run();