模板方法模式定义了算法的骨架,具体步骤由子类实现,使子类可自定义具体步骤而无需改变整体结构。此模式用于:1. 定义算法的骨架。2. 将算法的具体行为延迟到子类。3. 允许子类自定义算法的某些步骤,而无需更改算法的总体结构。
简介
模板方法模式是一种设计模式,它定义了算法的骨架,而具体步骤由子类具体实现。这使得子类可以自定义具体步骤,而无需改变算法的整体结构。
UML 图
+----------------+ | AbstractClass | +----------------+ | + templateMethod() | +----------------+ +----------------+ | ConcreteClass1 | +----------------+ | + concreteMethod1() | +----------------+ +----------------+ | ConcreteClass2 | +----------------+ | + concreteMethod2() | +----------------+
代码示例
AbstractClass.php
abstract class AbstractClass { public function templateMethod() { $this->step1(); $this->step2(); $this->hookMethod(); } protected abstract function step1(); protected abstract function step2(); protected function hookMethod() {} }
ConcreteClass1.php
class ConcreteClass1 extends AbstractClass { protected function step1() { echo "ConcreteClass1: Step 1<br>"; } protected function step2() { echo "ConcreteClass1: Step 2<br>"; } }
ConcreteClass2.php
class ConcreteClass2 extends AbstractClass { protected function step1() { echo "ConcreteClass2: Step 1<br>"; } protected function step2() { echo "ConcreteClass2: Step 2<br>"; } protected function hookMethod() { echo "ConcreteClass2: Hook Method<br>"; } }
实战案例
假设我们有一个学生管理系统,我们需要创建两个页面:“学生列表”页面和“学生详情”页面。这两个页面使用相同的布局,但具体内容不同。
StudentManager.php
class StudentManager { public function showStudentList() { $students = // 获取学生数据 $view = new StudentListView(); $view->setStudents($students); $view->render(); } public function showStudentDetail($id) { $student = // 获取学生数据 $view = new StudentDetailView(); $view->setStudent($student); $view->render(); } }
StudentListView.php
class StudentListView extends AbstractView { private $students; public function setStudents($students) { $this->students = $students; } public function render() { $this->showHeader(); $this->showStudents(); $this->showFooter(); } protected function showStudents() { echo "<h1>学生列表</h1>"; echo "<ul>"; foreach ($this->students as $student) { echo "<li>" . $student->getName() . "</li>"; } echo "</ul>"; } }
StudentDetailView.php
class StudentDetailView extends AbstractView { private $student; public function setStudent($student) { $this->student = $student; } public function render() { $this->showHeader(); $this->showStudent(); $this->showFooter(); } protected function showStudent() { echo "<h1>学生详情</h1>"; echo "<p>姓名:" . $this->student->getName() . "</p>"; echo "<p>年龄:" . $this->student->getAge() . "</p>"; } }
以上是PHP中如何使用模板方法模式?的详细内容。更多信息请关注PHP中文网其他相关文章!