Learning PHP Strategy Pattern - Quoted from 'In-depth PHP Object-Oriented Pattern and Practice'

WBOY
Release: 2016-08-08 09:28:30
Original
1001 people have browsed it
#策略(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/>";
}
Copy after login

The above introduces the learning of PHP strategy mode - quoted from "In-depth PHP Object-oriented Pattern and Practice", including aspects of the content, I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template