#策略(Strategy)模式
#定义抽象类 Lesson
abstract class Lesson{
private $duration;
private $coststrategy;#定义属性
public function __construct($duration , CostStrategy $strategy){
#实例化时,传进来一个对象
#用CostStrategy 类来处理 某个行为,而不用调用自身的方法来处理
$this->duration =$duration;
$this->coststrategy = $strategy;
}
public function cost(){
return $this->coststrategy->cost($this); # ??? ??? ??? ??? ??? ??? ??? ??? ???
}
#不是用抽象类的 abstract CostStrategy 类 中的方法 cost 来实现的,
#从输出的值看来 是用的
#TimedCostStrategy
#FixedCostStrategy 中 的方法,所以
# 在实例化对象时,用了
#TimedCostStrategy
#FixedCostStrategy 中 的方法
public function chargeType(){
return $this->coststrategy->chargeType();
}
public function getDuration(){
return $this->duration;
}
}
abstract class CostStrategy{ #抽象类是不能实例化的
abstract function cost( Lesson $lesson); #传入的参数是对象
abstract function chargeType();
}
class TimedCostStrategy extends CostStrategy{
public function cost(Lesson $lesson){
return ($lesson->getDuration()*5);
# 在Lesson 类中,getDuration 的返回值是 return $this->duration;
}
public function chargeType(){
return 'hourly rate!';
}
}
class FixedCostStrategy extends CostStrategy{
function cost(Lesson $lesson){
return 30;
#此处为调用如何方法,只是单纯的返回一个值
}
function chargeType(){
return 'fixed rate';
}
}
#继承类Lesson
class Lecture extends Lesson{
}
#继承类Lesson
class Seminar extends Lesson{
}
#实例化对象
$lessons[] = new Seminar(4,new TimedCostStrategy()); #生成了一个TimeConsTrategy的一个对象
$lessons[]= new Lecture(4 , new FixedCostStrategy());#生成了一个FixedConsTrategy的一个对象
#分别 调用TimeConsTrategy && FixedConsTrategy 中的方法 const() 和 chargeType(),在执行遍历
foreach ($lessons as $lesson) {
# 遍历输出
print "lesson charge {$lesson->cost()}==>>";
print "Charge type: {$lesson->chargeType()}
";
}
以上就介绍了php 策略模式的学习 --引自《深入php面向对象模式与实践》,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。 本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉 本文系统来源:php中文网