php 策略模式的学习 --引自《深入php面向对象模式与实践》

php中文网
发布: 2016-08-08 09:28:30
原创
1232人浏览过

#策略(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()}<br/>";
}
登录后复制

以上就介绍了php 策略模式的学习 --引自《深入php面向对象模式与实践》,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号