`
lanlansnss
  • 浏览: 44566 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

策略模式

    博客分类:
  • php
 
阅读更多
/**
 * 目前课程分为演讲 和研讨。
 * 收费有固定收费 和按照时间收费
 * 使用策略模式来解决收费 和 收费项目
 */

/**
 * lesson
 * abstract
 */
class  Lesson{
	private $duration;
	private $costStrategy;
	function __construct( $duration, CostStrategy $costStrategy ) {
		$this->duration     = $duration;
		$this->costStrategy = $costStrategy;
	}
	/*cost 委托给CostStrategy对象计算*/
	function cost() {
		return $this->costStrategy->cost( $this );
	}
	/*chargeType 委托给CostStrategy对象计算*/
	function chargeType() {
		return $this->costStrategy->chargeType( );
	}
	function getDuration() {
		return $this->duration;
	}
}

abstract class CostStrategy {
	abstract function cost( Lesson $lesson );
	abstract function chargeType(); 
}
class TimeCostStrategy extends CostStrategy {
	function cost( Lesson $lesson ) {
		return ( $lesson->getDuration() * 5 );
	}
	function chargetype() {
		return 'hourly';
	}
}
class fixedCostStrategy extends CostStrategy {
	function cost( Lesson $lesson ) {
		return 30;
	}
	function chargeType() {
		return 'fixed';
	}
	
}
/*打折项目*/
class discountCostStrategy extends CostStrategy {
	private $discount;
	private $costStrategy;
	function __construct( CostStrategy $costStrategy, $discount ) {
		$this->discount     = $discount;
		$this->costStrategy = $costStrategy;
	}
	function cost( Lesson $lesson ){
		return $this->costStrategy->cost( $lesson ) / ( $this->discount * 10 );
	}
	function chargeType() {
		return $this->costStrategy->chargeType();
	}
}
$lesson = new Lesson( '4', new discountCostStrategy( new fixedCostStrategy(), 7 ) );
var_dump( $lesson );
echo $lesson->cost(), $lesson->chargeType();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics