美文网首页
PHP 策略模式--按性别显示商品推荐

PHP 策略模式--按性别显示商品推荐

作者: wyc0859 | 来源:发表于2019-02-16 21:01 被阅读0次

4个PHP文件
index.php 主入口
app\UserStrategy.php 接口文件
app\FemaleUserStrategy.php 策略文件
app\MaleUserStrategy.php 策略文件

require 'App\UserStrategy.php';
require 'App\FemaleUserStrategy.php';
require 'App\MaleUserStrategy.php';
use App\UserStrategy;
use App\FemaleUserStrategy;
use App\MaleUserStrategy;

class Page{
    protected $strategy;
    function index(){
        $this->strategy->showAd();
        echo "<br/>";
        $this->strategy->showCategory();
    }
    function setStrategy(UserStrategy $strategy){
        $this->strategy=$strategy;
    }
}

$page=new Page;
if(isset($_GET['female'])){
    $strategy=new FemaleUserStrategy();
}else{
    $strategy=new MaleUserStrategy();
}
$page->setStrategy($strategy);
$page->index();
namespace App;
interface UserStrategy {
    function showAd();
    function showCategory();
} 
namespace App;
//策略模式-男
class MaleUserStrategy implements UserStrategy  {
    function showAd()    {
        echo "IPhone6";
    }
    function showCategory()    {
        echo "电子产品";
    }
} 
namespace App;
//策略模式-女
class FemaleUserStrategy implements UserStrategy {
    function showAd()    {
        echo "2014新款女装";
    }
    function showCategory()    {
        echo "女装";
    }
} 
可以看出page类与多个策略类是可以任意切换的,并不相互依赖,非耦合;策略模式实现了依赖倒置,解决了该类耦合问题

相关文章

网友评论

      本文标题:PHP 策略模式--按性别显示商品推荐

      本文链接:https://www.haomeiwen.com/subject/qxgieqtx.html