模板方法模式定義了演算法的骨架,具體步驟由子類別實現,使子類別可自訂特定步驟而無需改變整體結構。此模式用於: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中文網其他相關文章!