策略模式
将一组特定行为和算法封装成类,以适应某些特定的上下文环境。
实现
定义接口
interface Strategy{ public function showShop(); public function showAd(); }
针对不同的对象实现不同的策略。
策略一
class YangMan implements Strategy{ public function showShop() { // TODO: Implement showShop() method. echo '显示年轻人呢的商品'; } public function showAd() { // TODO: Implement showAd() method. echo "针对年轻人做的广告"; } }
策略二
class OldMan implements Strategy{
public function showShop()
{
// TODO: Implement showShop() method.
echo '显示老人呢的商品';
}
public function showAd()
{
// TODO: Implement showAd() method.
echo "针对老人做的广告";
}
实现策略
class StrategyComplete {
protected $strategy;
public function doSomething(){
$this->strategy->showShop();
echo "<br>";
$this->strategy->showAd();
}
public function setStrategy( Strategy $strategy){
$this->strategy = $strategy;
}
}
$obj = new StrategyComplete();
if($_GET['type']= 'oldman'){
$obj->setStrategy(new OldMan());
}else{
$obj->setStrategy(new OldMan());
}
$obj->doSomething();
小结:上一节是适配器模式,适配器是操作相同的对象,使用不同的方法,以达到兼容问题(操作可选择)。而策略模式是针对不同的对象显示不同东西(有点怀疑这句话),其实根据这个词“策略”,就感觉在谋划什么东西一样。
class OldMan implements Strategy{ public function showShop() { // TODO: Implement showShop() method. echo '显示老人呢的商品'; } public function showAd() { // TODO: Implement showAd() method. echo "针对老人做的广告";}
class StrategyComplete { protected $strategy; public function doSomething(){ $this->strategy->showShop(); echo "<br>"; $this->strategy->showAd(); } public function setStrategy( Strategy $strategy){ $this->strategy = $strategy; } } $obj = new StrategyComplete(); if($_GET['type']= 'oldman'){ $obj->setStrategy(new OldMan()); }else{ $obj->setStrategy(new OldMan()); } $obj->doSomething();
视频链接免费:http://www.imooc.com/learn/236