/**
* 目前课程分为演讲 和研讨。
* 收费有固定收费 和按照时间收费
* 使用策略模式来解决收费 和 收费项目
*/
/**
* 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();
策略模式
最新推荐文章于 2023-06-11 15:10:32 发布