策略模式

定义:将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,使用策略模式可以实现Ioc,依赖倒置、控制反转
实际应用举例:假如一个电商网站系统,针对男性女性的用户要各自跳转到不同商品类目,并且所有广告位展示不同的广告(分支逻辑)

class Page
{
protected $strategy;
function index()
{
echo "AD:";
$this->strategy->showAd();
echo "<br/>";

echo "category:";
$this->strategy->showCategory();
echo "<br/>";

}

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();

<?php
namespace IMooc;

interface UserStrategy
{
function showAd();
function showCategory();
}

<?php
namespace IMooc;


class FemaleUserStrategy implements UserStrategy
{

function showAd()
{
echo "2016新款女装";
}

function showCategory()
{
echo "女装";
}
}

<?php
namespace IMooc;


class MaleUserStrategy implements UserStrategy
{

function showAd()
{
echo "IPhone6";
}

function showCategory()
{
echo "电子产品";
}
}



来自为知笔记(Wiz)


posted on 2016-12-24 22:12  果然朝辉  阅读(106)  评论(0编辑  收藏  举报

导航