一般用 if else 判断,,这是硬编码。如果某一天,
增加了针对小孩的广告,就得修改 if else 的代码。
UserStrategy.php
<?php
//策略接口文件,约定了策略有哪些行为
namespace IMooc;
interface UserStrategy
{
//有2个策略,一个展示广告,二是展示分类
public function showAd();
public function showCategory();
}
FemaleUserStrategy.php
<?php
//具体策略的实现,针对女性用户
namespace IMooc;
class FemaleUserStrategy implements UserStrategy
{
public function showAd()
{
echo '2014新款女装';
}
public function showCategory()
{
echo '女装';
}
}
MaleUserStrategy.php
<?php
//具体策略的实现,针对男性用户
namespace IMooc;
class MaleUserStrategy implements UserStrategy
{
public function showAd()
{
echo 'iphone 6';
}
public function showCategory()
{
echo '电子产品';
}
}
index.php
<?php
define('BASEDIR',__DIR__);
include BASEDIR . '/IMooc/Loader.php';
spl_autoload_register('\\IMooc\\Loader::autoload');
class Page
{
protected $strategy;
public function index()
{
//传统方法,if else
/*if(isset($_GET['female'])){
}elseif(isset($_GET['male'])){
}*/
//现在只需调用策略对象提供的行为方法
echo "AD:";
$this->strategy->showAd();
echo '<br/>';
echo "Category:";
$this->strategy->showCategory();
}
//给外部调用,来设置策略
public function setStrategy(\IMooc\UserStrategy $strategy) //约定接口类型
{
$this->strategy = $strategy;
}
}
$page = new Page();
//根据实际上下文环境,传入策略对象
if(isset($_GET['female'])){
$strategy = new IMooc\FemaleUserStrategy();
}else{
$strategy = new IMooc\MaleUserStrategy();
}
$page->setStrategy($strategy);
$page->index();
Page 类 中调用了 MaleUserStrategy,FemaleUserStrategy ,也就是说它依赖 这些类 。
通过接口的设置,策略的解耦,在代码中把依赖关系进行了反转。
所以,在写 Page 类的时候,并不需要写依赖类的代码的实现,
在执行中,才将关系进行绑定。面向对象中,很重要的就是解耦。
如果两个类是互相依赖的关系,那么它们之间就是紧耦合的设计,
这样就不利于我们替换其中某个环节。使用策略模式进行依赖倒置之后,
就可以很方便的替换掉其中的某个类。