2021-01-04

12 篇文章 0 订阅
5 篇文章 0 订阅

策略模式(Strategy)

策略模式定义

策略模式是把算法,封装起来。使得使用算法和使用算法环境分离开来,当算法发生改变时,我们之需要修改客户端调用算法,和增加一个新的算法封装类。比如超市收银,收营员判断顾客是否是会员,当顾客不是会员时候,按照原价收取顾客购买商品费用,当顾客是会员的时候,满100减5元。

策略模式的优点

  • 降低代码耦合度,
  • 增加代码重用性,当需要实现新的算法时候,只需要修改算法部分,而不需要对上下文环境做任何改动;
  • 增加代码可阅读性,避免使用if…else嵌套,造成难以理解的逻辑;

策略模式的缺点

  • 当策略过多的时候,会增加很多类文件;

代码实现

Cashier.php

<?php


namespace App\Creational\Strategy;


class Cashier
{

    private $cutomer;

    public function setStrategy(CustomerAbstract $customer)
    {
        $this->cutomer = $customer;
    }

    public function getMoney($price)
    {
        return $this->cutomer->pay($price);
    }
}

CustomerAbstract.php

<?php


namespace App\Creational\Strategy;


abstract class CustomerAbstract
{
    abstract public function pay($price);
}

NormalCustomer.php

<?php


namespace App\Creational\Strategy;


class NormalCustomer extends CustomerAbstract
{

    public function pay($price)
    {
        return $price;
    }
}

VipCustomer.php

<?php


namespace App\Creational\Strategy;


class VipCustomer extends CustomerAbstract
{

    public function pay($price)
    {
        return $price - floor($price/100)*5;
    }

}

测试代码
StrategyTest.php

<?php

/**
 * 策略模式
 * Class StrategyTest
 */

class StrategyTest extends \PHPUnit\Framework\TestCase
{

    public function testCustomer()
    {
        $price = 100;

        $vipCutomer = new \App\Creational\Strategy\VipCustomer();
        $normalCustomer = new \App\Creational\Strategy\NormalCustomer();

        $cashier = new \App\Creational\Strategy\Cashier();

        $cashier->setStrategy($vipCutomer);
        $this->assertEquals(95, $cashier->getMoney($price));

        $cashier->setStrategy($normalCustomer);
        $this->assertEquals(100, $cashier->getMoney($price));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值