策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。
女性用户类
class FemaleUserStrategy implements UserStrategy
{
function showAd()
{
// TODO: Implement showAd() method.
echo "2020新款女装";
}
function showCategory()
{
// TODO: Implement showCategory() method.
echo "女装";
}
}
男性用户类
class MaleUserStrategy implements UserStrategy
{
function showAd()
{
// TODO: Implement showAd() method
echo "Iphone 6";
}
function showCategory()
{
// TODO: Implement showCategory() method.
echo "数码产品";
}
}
场景
class Page{
protected $strategy;
function index(){
echo 'AD:';
$this->strategy->showAd();
echo "<br>";
echo "类目:";
$this->strategy->showCategory();
}
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();