实现功能:
扣除用户金币及写入金币明细,这是同一个行为,使用外观模式
金币明细需要多个参数来保证对象的完整,参数过多,所以使用建造模式
一.用户明细类
class MoneyDetail { const MONEY_PAY = 1; // 充值获得 const MONEY_EXCHANGE = 2; // 兑换 private $type; private $quantity; private $desc; private $time; public function __construct(MoneyDetailBuilder $builder) { $this->type = $builder->getType(); $this->quantity = $builder->getQuantity(); $this->desc = $builder->getDesc(); $this->time = $builder->getTime(); } /** * 写入数据库 */ public function writeDb() { echo "[{$this->type}|{$this->quantity}|{$this->desc}|{$this->time}]数据已写入数据库"; } }
二.用户明细建造者类
class MoneyDetailBuilder { private $type; private $quantity; private $desc; private $time; /** * @return mixed */ public function getType() { return $this->type; } /** * @param $type * @return $this */ public function setType($type) { $this->type = $type; return $this; } /** * @return mixed */ public function getQuantity() { return $this->quantity; } /** * @param $quantity * @return $this */ public function setQuantity($quantity) { $this->quantity = $quantity; return $this; } /** * @return mixed */ public function getDesc() { return $this->desc; } /** * @param $desc * @return $this */ public function setDesc($desc) { $this->desc = $desc; return $this; } /** * @return mixed */ public function getTime() { return $this->time; } /** * @param $time * @return $this */ public function setTime($time) { $this->time = $time; return $this; } public function moneyDetail() { return new MoneyDetail($this); } }
三.用户类:
class User { private $money; public function __construct() { $this->money = 500; } public function reduceMoney($quantity) { $this->money -= $quantity; echo ‘用户扣除金币成功‘; } public function getMoney() { return $this->money; } }
四.扣除用户金币外观类
class UserFacade { private $user; private $moneyDetailBuilder; public function __construct(User $user, MoneyDetailBuilder $moneyDetailBuilder) { $this->user = $user; $this->moneyDetailBuilder = $moneyDetailBuilder; } public function reduceMoney($quantity) { $this->user->reduceMoney($quantity); $this->moneyDetailBuilder->setDesc($this->moneyDetailBuilder->getDesc() . "扣除{$quantity}金币;当前金币{$this->user->getMoney()}"); $this->moneyDetailBuilder->moneyDetail()->writeDb(); } }
五.调用
// 建造金币明细类 $moneyDetailBuilder = new MoneyDetailBuilder(); $moneyDetailBuilder->setType(MoneyDetail::MONEY_EXCHANGE) ->setQuantity(100) ->setTime(time()) ->setDesc(‘兑换奖品,‘); // 扣除金币 $user = new User(); $userFacade = new UserFacade($user, $moneyDetailBuilder); $userFacade->reduceMoney(100);
原文地址:https://www.cnblogs.com/itfenqing/p/8728938.html
时间: 2024-10-13 06:55:20