The template pattern prepares an abstract class, implements part of the logic in the form of concrete methods and concrete constructs, and then declares some abstract methods to force the subclass to implement the remaining logic. Different subclasses can implement these abstract methods in different ways and thus have different implementations of the remaining logic. Develop a top-level logic framework first, and leave the details of the logic to specific subclasses.
UML class diagram:
Character:
Abstract Template Role (MakePhone): Abstract template class defines a specific algorithm process and some abstract methods that must be implemented by subclasses.
Concrete subclass role (XiaoMi): implements the abstract method in MakePhone. The subclass can have its own unique implementation form, but the execution process is controlled by MakePhone.
Core code:
<!--?php /** * Created by PhpStorm---> * User extends Jang * Date extends 2015/6/10 * Time extends 11 extends 06 */ //抽象模板类 abstract class MakePhone { protected $name; public function __construct($name) { $this->name=$name; } public function MakeFlow() { $this->MakeBattery(); $this->MakeCamera(); $this->MakeScreen(); echo $this->name.手机生产完毕!
header(Content-Type:text/html;charset=utf-8); //-------------------------模板模式--------------------- require_once ./Template/Template.php; $miui=new XiaoMi(); $flyMe=new FlyMe(); $miui->MakeFlow(); $flyMe->MakeFlow();
Applicable scenarios and advantages:
1. Complete a process or a series of steps with a consistent level of detail, but the implementation of individual steps at a more detailed level may be different at the same time. We usually consider using the template pattern to deal with it.
2. When immutable and variable behaviors are mixed together in the subclass implementation of a method, the immutable behavior will appear repeatedly in the subclass. We use the template pattern to move these behaviors to a single place, thus helping subclasses get rid of the tangle of repeated immutable behavior.
3. The template pattern reflects its advantages by moving unchanged behaviors to super abstract classes and removing duplicate code in subclasses. The template pattern provides a good platform for code reuse.
Welcome to follow my video course, the address is as follows, thank you.
PHP object-oriented design patterns