模板方法模式,是最为常见,也是使用最为广泛的一种设计模式,很多程序猿都不知道,自己随便写的代码,也是一种设计模式。如果只能学习一种设计模式的话,那么就应该学习模板模式。
模板模式:在一个方法里定义算法的骨架,将一些步骤延迟到其子类。顾名思义,模板模式,就是有一个固定的,现成的模板,往里面套东西呗。比如PPT,WORD,EXCEL等,Microsoft为我们提供了大量的模板。可以直接套用,也可以略做修改。总之,比我们自己全新做要省很多事儿。
抽出多个类的共同特性,成为一个父类,父类根据需求封装好一个算法骨架,然后子类调用父类即可。
以PHP为代码环境,

<?php
class TestPaper{
    public $name;
    public $classes;
    public function __construct($name, $classes){
        $this->name = $name;
        $this->classes = $classes;
    }
    public function display(){
        echo '姓名:' . $this->name . ', 班级:' . $this->classes;
        $this->separate();
    }
    public function title1($answer){
        echo '题目一:******';
        echo '答案:' . $this->answer($answer);
        $this->separate();
    }
    public function title2($answer){
        echo '题目二:******';
        echo '答案:' . $this->answer($answer);
        $this->separate();
    }
    public function answer($answer){
        return $answer;
    }
    public function separate(){
        echo '<br>';
    }
}
class studentA extends TestPaper{
    public function __construct($name, $classes){
        parent::__construct($name, $classes);
    }
    public function answerTestPaper(){
        $this->display();
        $this->title1('C');
        $this->title1('B');
    }
}
class studentB extends TestPaper{
    public function __construct($name, $classes){
        parent::__construct($name, $classes);
    }
    public function answerTestPaper(){
        $this->display();
        $this->title1('A');
        $this->title1('D');
    }
}
$studentA = new studentA('小明', '一');
$studentA->answerTestPaper();
$studentB = new studentB('小红', '二');
$studentB->answerTestPaper();
?>

标签: PHP, 设计模式, 模板方法模式

添加新评论