PHP设计模式 -- 策略模式

策略模式:

  6、将一组特定的行为和算法封装成类,以适应某些特定的上下文环境。

  1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。

       2、 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。

       3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

       4、客户端必须知道所有的策略类,并自行决定使用哪一个策略类,策略模式只适用于客户端知道所有的算法或行为的情况。

       5、 策略模式造成很多的策略类,每个具体策略类都会产生一个新类。  

 
场景:假如有一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有的广告位展示不同的广告。在传统的代码中,都是在系统中加入各种if else的判断,硬编码的方式。如果有一天增加了一种用户,就需要改写代码。使用策略模式,如果新增加一种用户类型,只需要增加一种策略就可以。其他所有的地方只需要使用不同的策略就可以。 
首先声明策略的接口文件,约定了策略的包含的行为。然后,定义各个具体的策略实现类。

示例:

<?php

// 声明策略文件的接口,约定策略包含的行为。
interface UserStrategy
{
    public function showA();
    public function showB();
}


//  具体策略角色(ItemX):包装了相关的算法和行为。
class Man implements UserStrategy
{
    public function showA()
    {
        echo 'this is man';
    }

    public function showB()
    {
        echo 'The man is strong';
    }
}


//  具体策略角色(ItemX):包装了相关的算法和行为。
class Wuman implements UserStrategy
{
    public function showA()
    {
        echo 'This is wuman';
    }

    public function showB()
    {
        echo 'The wuman is beautiful';
    }
}


// 环境角色(ItemContext):持有一个策略类的引用,最终给客户端调用
class Role
{
    private $Strategy;

    public function index()
    {
        $this->strategy->showA();
        echo "<br>";
        $this->strategy->showB();
    }

    public function setStrategy(UserStrategy $strategy)
    {
        $this->strategy = $strategy;
    }
}

$r = new Role;
if (isset($_GET['wuman'])) {
    $strategy = new Wuman;
} else {
    $strategy = new Man;
}

$r->setStrategy($strategy);
$r->index();

测试结果:

扫描二维码关注公众号,回复: 950855 查看本文章

1、没有get参数时

2、有get参数时

猜你喜欢

转载自www.cnblogs.com/chenhaoyu/p/9063454.html