码迷,mamicode.com
首页 > 其他好文 > 详细

责任链模式实例:扣除用户金币/写入金币明细/发送消息

时间:2018-04-06 23:41:23      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:obj   sha   strong   失败   handler   catch   写入   const   ted   

功能:

扣除用户金币,写入明细,并发送消息

以上三个动作任意一个动作失败,则请求终止

 

一.定义一个异常类:

class HandleException extends Exception
{
}

  

二.定义一个虚拟类:

abstract class Handle
{
    protected $nextHandle;

    public function setNextHandle(Handle $handle)
    {
        $this->nextHandle = $handle;
    }

    abstract public function handleRequest($request);
}

  

三.用户金币类:

class UserMoney extends Handle
{
    private $uid;
    private $money;

    public function __construct($uid, $money)
    {
        $this->uid      = $uid;
        $this->money    = $money;
    }

    public function handleRequest($request)
    {
        if ($this->money >= $request->money) {
            echo ‘扣除金币成功<br>‘;
            $this->money -= $request->money;

            // 给请求附加新的金币,便于金币明细记录
            $request->newMoney = $this->money;

            if ($this->nextHandle) {
                $this->nextHandle->handleRequest($request);
            }
        } else {
            throw new HandleException(‘金币不足‘, 2001);
        }
    }
}

  

四.金币明细类:

/**
 * 金币明细
 * Class UserMoneyDetail
 */
class UserMoneyDetail extends Handle
{
    public function writeDb($request)
    {
        echo "写入金币明细成功,新的金币数目为{$request->newMoney}<br>";
        return true;
    }

    public function handleRequest($request)
    {
        if ($this->writeDb($request)) {
            if ($this->nextHandle) {
                $this->nextHandle->handleRequest($request);
            }
        } else {
            throw new HandleException(‘金币不足‘, 2002);
        }
    }
}

  

五.发送消息类:

class Message extends Handle
{
    public function sendMessage($request)
    {
        echo "UID为{$request->uid}的用户减少了{$request->money}金币,减少的后金币为{$request->newMoney}";
        return true;
    }

    public function handleRequest($request)
    {
        if (! $this->sendMessage($request)) {
            throw new HandleException(‘发送邮件出错‘, 2003);
        }
    }
}

  

六.调用

$request = (object) [‘uid‘ => 10, ‘money‘ => 500];

try {
    $userMoney          = new UserMoney($request->uid, 300);
    $userMoneyDetail    = new UserMoneyDetail();
    $message            = new Message();

    $userMoney->setNextHandle($userMoneyDetail);
    $userMoneyDetail->setNextHandle($message);

    $userMoney->handleRequest($request);
} catch (HandleException $e) {
    echo "发生错误:{$e->getMessage()}";
}

  

 

责任链模式实例:扣除用户金币/写入金币明细/发送消息

标签:obj   sha   strong   失败   handler   catch   写入   const   ted   

原文地址:https://www.cnblogs.com/itfenqing/p/8729024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!