模板方法模式定义了算法的骨架,具体步骤由子类实现,使子类可自定义具体步骤而无需改变整体结构。此模式用于:1. 定义算法的骨架。2. 将算法的具体行为延迟到子类。3. 允许子类自定义算法的某些步骤,而无需更改算法的总体结构。
PHP 中的模板方法模式
简介
模板方法模式是一种设计模式,它定义了算法的骨架,而具体步骤由子类具体实现。这使得子类可以自定义具体步骤,而无需改变算法的整体结构。
UML 图
立即学习“PHP免费学习笔记(深入)”;
+----------------+| 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
"; } protected function step2() { echo "ConcreteClass1: Step 2
"; }}
登录后复制
ConcreteClass2.php
class ConcreteClass2 extends AbstractClass{ protected function step1() { echo "ConcreteClass2: Step 1
"; } protected function step2() { echo "ConcreteClass2: Step 2
"; } protected function hookMethod() { echo "ConcreteClass2: Hook Method
"; }}
登录后复制
实战案例
假设我们有一个学生管理系统,我们需要创建两个页面:“学生列表”页面和“学生详情”页面。这两个页面使用相同的布局,但具体内容不同。
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 "学生列表
"; echo "
登录后复制”; foreach ($this->students as $student) { echo “” . $student->getName() . “”; } echo “”; }}
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 "学生详情
"; echo "姓名:" . $this->student->getName() . "
"; echo "年龄:" . $this->student->getAge() . "
"; }}
登录后复制
以上就是PHP中如何使用模板方法模式?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/1718219.html