实现功能:

用户抽奖消耗相应银两,将银两明细写入数据库,(为示例简单,体现模式意图,我们假定用户抽奖一定会中奖),将抽中的银两增加给用户也写入数据库

 

一.银两类:

class Silver
{
    const RULE_ADD = 1;
    const RULE_REDUCE = 2;

    private $uid;
    private $type;
    private $rule;
    private $quantity;
    private $desc;
    private $time;

    public function __construct($uid,$type, $rule, $quantity, $desc, $time)
    {
        $this->uid      = $uid;
        $this->type     = $type;
        $this->rule     = $rule;
        $this->quantity = $quantity;
        $this->desc     = $desc;
        $this->time     = time();
    }

    /**
     * @param mixed $quantity
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
    }

    /**
     * @param mixed $desc
     */
    public function setDesc($desc)
    {
        $this->desc = $desc;
    }

    /**
     * @param mixed $rule
     */
    public function setRule($rule)
    {
        $this->rule = $rule;
    }

    public function writeToDb()
    {
        // 模拟写入数据库
        echo "{$this->uid}|{$this->type}|{$this->rule}|{$this->quantity}|{$this->desc}|{$this->time}已写入数据库<br>";
        return true;
    }
}

  

二.抽奖类

class Lottery
{
    const SILVER_TYPE               = 1;
    const SILVER_ADD_QUANTITY       = 20;
    const SILVER_REDUCE_QUANTITY    = 10;

    private $uid;
    private $silver;

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

    // 抽奖
    public function run()
    {
        // 处理其他逻辑....

        /**
         * 将扣除用户的银两写入记录
         */
        $this->silver   = new Silver(
            $this->uid,
            self::SILVER_TYPE,
            Silver::RULE_REDUCE,
            self::SILVER_REDUCE_QUANTITY,
            '抽奖扣除银两',
            time()
        );

        // 处理其他逻辑....

        /**
         * 使用原型模式,直接clone一个银两类
         * 将用户抽奖获得的银两写入记录
         */
        $addSilver       = clone $this->silver;
        $addSilver->setRule(Silver::RULE_ADD);
        $addSilver->setQuantity(self::SILVER_ADD_QUANTITY);
        $addSilver->setDesc('抽奖中奖');

        if ($this->silver->writeToDb() && $addSilver->writeToDb()) {
            echo '<hr>抽奖成功!';
        }
    }
}

  

三.调用

$lottery = new Lottery(10);
$lottery->run();