模板方法模式

在父类中定义处理流程的框架,在子类中实现具体处理。

类图

2024061015425445.png

代码示例

<?php
 
abstract class AbstructClass
{
abstract public function step1();
abstract public function step2();
abstract public function step3();
final public function initStep()
{
echo "initStep\n";
}
final public function endStep()
{
echo "endStep\n";
}
public function afterEndStep()
{
echo "afterEndStep\n";
}
final public function templateMethod()
{
$this->initStep();
$this->step1();
$this->step2();
$this->step3();
$this->endStep();
}
}
 
class A extends AbstructClass
{
public function step1()
{
echo "A::step1\n";
}
public function step2()
{
echo "A::step2\n";
}
public function step3()
{
echo "A::step3\n";
}
public function afterEndStep()
{
echo "A::afterEndStep\n";
}
}
 
class B extends AbstructClass
{
public function step1()
{
echo "B::step1\n";
}
public function step2()
{
echo "B::step2\n";
}
public function step3()
{
echo "B::step3\n";
}
public function afterEndStep()
{
echo "B::afterEndStep\n";
}
}
 
function client(AbstructClass $obj)
{
//
}
 
 
$a = new A();
$b = new B();
 
client($a);
client($b);