将一组特定的行为和算法封装成类,以适应某些特定的上下文环境.这种模式就是策略模式.

<?php
namespace Lib;

interface UserStrategy{
    function showAd();
    function showCategory();
}
<?php
//男性策略类
namespace Lib;

class ManStrategy implements \Lib\UserStrategy
{
    public function showAd()
    {
        echo "游戏";
    }

    public function showCategory()
    {
        echo "理财";
    }
}
<?php
//女性策略类
namespace Lib;

class WomanStrategy implements \Lib\UserStrategy
{
    public function showAd()
    {
        echo "动漫";
    }

    public function showCategory()
    {
        echo "购物";
    }
}
<?php
//页面展示类
namespace Lib;

class Page
{
    private $strategy;

    public function setContext(\Lib\UserStrategy $userStrategy)
    {
        $this->strategy = $userStrategy;
    }

    public function action()
    {
        $this->strategy->showCategory();
    }
}
$page = new \Lib\Page();
//根绝条件执行
$page->setContext(new \Lib\WomanStrategy());

$page->action();

results matching ""

    No results matching ""

    results matching ""

      No results matching ""