1. Pattern definition
Template method mode is also called template mode, which defines the skeleton of an algorithm in one method, and delays some steps into subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.
The template method pattern defines the primary method as final, prevents subclasses from modifying the algorithm skeleton, and defines the method that the subclass must implement as abstract. A common method (no final or abstract modification) is called a hook.
2. UML Class Diagram
3. Sample Code
journey.php
Buyaflight (); $this->takeplane (); $this->enjoyvacation (); $this->buygift (); $this->takeplane (); } /** * This method must be implemented by the quilt class, which is the core feature of the template method mode * /abstract protected function enjoyvacation (); /** * This method is also part of the algorithm, but it is optional, only to rewrite it when needed * /protected function Buygift () { } /** * Subclass cannot access the method * /Private Function buyaflight () { echo "Buying a flight\n"; } /** * This is also a final method * /FINAL protected function Takeplane () { echo "taking the plane\n"; }}
beachjourney.php
cityjourney.php
4. Test code
tests/journeytest.php
Expectoutputregex (' #sun-bathing# '); $journey->takeatrip (); Public Function testcity () {$journey = new Templatemethod\cityjourney (); $this->expectoutputregex (' #drink # '); $journey->takeatrip (); }/** * How to test the abstract template method in PHPUnit */Public Function Testlasvegas () {$journey = $this->getmockforabs Tractclass (' Designpatterns\behavioral\templatemethod\journey '); $journey->expects ($this->once ())->method (' Enjoyvacation ')->will ($this->returncallba CK (Array ($this, ' mockupvacation '))); $this->expectoutputregex (' #Las vegas# '); $journey->takeatrip (); } public Function Mockupvacation () {echo ' Fear and Loathing in Las vegas\n '; }}
5. Summary
Template method pattern is an inheritance-based code reuse technique, and the structure and usage of template method pattern are also the core of object-oriented design. In the template method pattern, you can put the same code in the parent class and put different method implementations in different subclasses.
In the template method pattern, we need to prepare an abstract class that implements some of the logic in the form of concrete methods and concrete constructors, and then declares some abstract methods for subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic, which is the intent of the template method pattern. The template method pattern embodies many important ideas of object-oriented, and is a mode with high frequency.