模板模式

当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其个别步骤在更详细的层次上的实现可能不同时,我们通常考虑用模板方法模式来处理

 

<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/2/7
* Time: 16:47
*/

namespace frontend\models;


class TestPaper
{

public function TestQuestion1(){

echo '问题1<br>';

echo '答案为'.$this->Answer1().'<br>';
}
public function TestQuestion2(){

echo '问题2<br>';

echo '答案为'.$this->Answer2().'<br>';
}
public function TestQuestion3(){

echo '问题3<br>';

echo '答案为'.$this->Answer3().'<br>';
}

public function Answer1(){

return '';
}
public function Answer2(){

return '';
}
public function Answer3(){

return '';
}


}

<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/2/7
* Time: 16:53
*/

namespace frontend\models;


class TestPaperA extends TestPaper
{

public function Answer1(){

return 'A';
}
public function Answer2(){

return 'B';
}
public function Answer3(){

return 'C';
}

}

<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/2/7
* Time: 16:54
*/

namespace frontend\models;


class TestPaperB extends TestPaper
{
public function Answer1(){

return 'C';
}
public function Answer2(){

return 'A';
}
public function Answer3(){

return 'B';
}

}

$test1 = new TestPaperA();

$test2 = new TestPaperB();

$test1->TestQuestion1();
$test1->TestQuestion2();
$test1->TestQuestion3();

$test2->TestQuestion1();
$test2->TestQuestion2();
$test2->TestQuestion3();

模板方法模式是通过把不变行为搬移到超类,去除子类中的重复代码来提现它的优势。有时候我们会遇到由一系列步骤构成的过程需要执行。这个过程从高层次上看是相同的,但有些步骤的实现可能不同。这时候,我们通常就应该要考虑用模板方法模式了。

posted on 2018-02-07 17:14  paulversion  阅读(103)  评论(0编辑  收藏  举报