The template method pattern is a behavioral pattern that defines the skeleton of an algorithm in an operation and defers some steps to subclasses. Template Method allows subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm.
Main role
Abstract template (AbstractClass) role
Define one or more abstract methods for subclasses to implement. These abstract methods are called basic operations, and they are components of top-level logic.
Define a template method. This template method is generally a concrete method, which gives the skeleton of the top-level logic, and the logical composition steps are in the corresponding abstract operations, and these operations will be postponed to subclasses. At the same time, the top-level logic can also call specific implementation methods
Concrete template (ConcrteClass) role
implement one or more abstract methods of the parent class, which exist as a component of the top-level logic.
Each abstract template can have multiple concrete templates corresponding to it, and each concrete template has its own implementation of abstract methods (that is, components of top-level logic), making the implementation of top-level logic different.
Applicability
Implement the immutable parts of an algorithm once and leave the variable behavior to subclasses.
Common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication.
Control subclass extension.
Class diagram
Instance
<?php abstract class AbstractClass { // 抽象模板角色 public function templateMethod() { // 模板方法 调用基本方法组装顶层逻辑 $this->primitiveOperation1(); $this->primitiveOperation2(); } abstract protected function primitiveOperation1(); // 基本方法 abstract protected function primitiveOperation2(); } class ConcreteClass extends AbstractClass { // 具体模板角色 protected function primitiveOperation1() {} protected function primitiveOperation2(){} } $class = new ConcreteClass(); $class->templateMethod(); ?>