Template method Mode:
Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. Templatemethod allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
Role:
Abstract template role: Abstract template class, which defines a specific algorithm flow and some abstract methods that must be implemented for subclasses.
Specific subclass roles: Implement abstract methods in abstract template classes, subclasses can have their own unique implementation form, but the execution process is controlled by the abstract template class.
UML diagram:
Applicability:
1, complete a level of detail a process or a series of steps, but its individual steps at a more detailed level of implementation may not be the same. We usually consider using template mode for processing.
2, when the invariant and variable behavior in the subclass implementation of the method is mixed together, the invariant behavior will be repeated in the subclass, we use template mode to move these behaviors to a single place, so as to help the subclass out of the repetition of the constant behavior of entanglement.
3, template mode by moving the invariant behavior to the Super abstract class, remove the duplicate code in the subclass to reflect its advantages. Template mode provides a good code reuse platform.
Code implementation:
<?PHP//abstract template class:Abstract classmakecomputer{Private $type; function__construct ($type){ $this->type =$type; } functionprocedure () {$this-Preparescreen (); $this-Preparemainboard (); $this-preparecpu (); $this-Preparememorybank (); } Abstract functionPreparescreen (); Abstract functionPreparemainboard (); Abstract functionpreparecpu (); Abstract functionPreparememorybank ();}classMakelenovocomputerextendsmakecomputer{function__construct ($type= ' Lenovo ') {Parent:: __construct ($type); } functionPreparescreen () {Echo"Lenovo Screen ready to complete"; } functionPreparemainboard () {Echo"Lenovo Motherboard ready to complete"; } functionpreparecpu () {Echo"Lenovo CPU ready to complete"; } functionPreparememorybank () {Echo"Lenovo Memory strips Ready"; }}classMakeasuscomputerextendsmakecomputer{function__construct ($type= ' asus ') {Parent:: __construct ($type); } functionPreparescreen () {Echo"ASUS Screen ready to complete"; } functionPreparemainboard () {Echo"ASUS Motherboard ready to complete"; } functionpreparecpu () {Echo"ASUS CPU ready to complete"; } functionPreparememorybank () {Echo"Asus Memory strips Ready"; }}//Test$lenovoComputer=NewMakelenovocomputer ();$lenovoComputer-procedure ();?>
Template method mode and PHP implementation