Template Method Pattern:
The Template Method pattern defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps. Template method pattern: Define the skeleton of an
algorithm in a method, and defer some steps to subclasses. The template method allows subclasses to Redefine certain steps in the algorithm.
##
'; } abstract class TemplateBase { abstract function step1(); abstract function step2(); abstract function step3(); public function doAction() { $this->step1(); if(!$this->skipStep2()) { $this->step2(); } $this->step3(); } /** * 钩子方法 */ public function skipStep2() { return false; } } class ConcreteTemplate extends TemplateBase { public function step1() { echoLine('This is step 1'); } public function step2() { echoLine('This is step 2'); } public function step3() { echoLine('This is step 3'); } // 用来控制是否跳过某些步骤 public function skipStep2() { return false; } } // test code $ct = new ConcreteTemplate(); $ct->doAction();
The above is the detailed content of Example code sharing of PHP template method pattern. For more information, please follow other related articles on the PHP Chinese website!