<?php
namespace Tools;
/*
策略模式
将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式
策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
*/
//定义一个策略接口
interface userStrategy{
function showAd(); //广告展示
function showCategory();//类目展示
}
//男性用户策略
class MaleUserStrategy implements userStrategy{
function showAd(){
echo "男性用户广告展示";
}
function showCategory()
{
echo "男性用户类目展示";
}
}
//女性用户策略
class FemaleUserStrategy implements userStrategy{
function showAd(){
echo "女性用户广告展示";
}
function showCategory(){
echo "女性用户类目展示";
}
}
//策略模式使用
class page{
protected $startegy;
//注入策略(只要实现了userstrategy接口的都是可注入的策略)
function setStrategy(\Tools\userStrategy $strategy){
$this->startegy = $strategy;
}
//显示
function show(){
$this->startegy->showAd();
echo "<br>";
$this->startegy->showCategory();
}
}
//根据参数展示不同的显示策略
$p = new \Tools\page();
if(isset($_GET["female"])){
$strategy = new \Tools\FemaleUserStrategy();
}else{
$strategy = new \Tools\MaleUserStrategy();
}
//注入策略
$p->setStrategy($strategy);
$p->show();