<?php //策略模式就是你有很多的方法,选择一种适合自己的, // 单例模式就是只有一个实例对象,不需要每个文件都要加载,比如连接数据库, // 工厂模式就是
//策略模式 优惠系统、工资计算系统 //工厂模式 主要应用在多数据库选择,类库文件加载等
//商场收银系统有正常收费,打折收费,返利收费模式 interface cashStrategy{ public function acceptCash($money); } //正常收费 class NormalStrategy implements cashStrategy{ public function acceptCash($money){ return $money; } } //打折收费 class RebateStrategy implements cashStrategy{ //打折比例 private $moneyRebate = 1; public function __construct($rebate){ $this->moneyRebate = $rebate; } public function acceptCash($money){ return $this->moneyRebate*$money; } } //返利收费 class ReturnStrategy implements cashStrategy{ //返利条件 private $moneyCondition = null; //返利多少 private $moneyReturn = null; public function __construct($moneyCondition ,$moneyReturn){ $this->moneyCondition = $moneyCondition; $this->moneyReturn = $moneyReturn; } public function acceptCash($money){ if(!isset($this->moneyCondition) || !isset($this->moneyReturn) || $this->moneyCondition == 0) return $money; return $money - floor($money/$this->moneyCondition)*$this->moneyReturn; } }
// 加载所有的策略
// 创建一个环境类,根据不同的需求调用不同策略 class Factory{ private $_strategy = null; public function __construct($type = null){ if(!isset($type)) return; $this->setCashStrategy($type);
} public function setCashStrategy($type){ $cs = null; switch($type){ case 'normal': $cs = new NormalStrategy(); break; case 'rebate8': $cs = new RebateStrategy(0.8); break; case 'return300to100': $cs = new ReturnStrategy(300,100); break; } $this->_strategy = $cs; } //获取结果 public function getResult($money){ return $this->_strategy->acceptCash($money); } public function getResultAll($type, $num, $price){ $this->setCashStrategy($type); return $this->getResult($num * $price); }
}
/* * 客户端类 * 让客户端和业务逻辑尽可能的分离,降低客户端和业务逻辑算法的耦合, * 使业务逻辑的算法更具有可移植性 */ class Client{
public function main(){ $total = 0;
$factory = new Factory();
// 购买数量 $numA = 10; // 单价 $priceA = 100; // 策略模式获取结果 $totalA = $factory->getResultAll('normal', $numA, $priceA); $this->display('A', 'normal', $numA, $priceA, $totalA);
// 购买数量 $numB = 5; // 单价 $priceB = 100; // 打折策略获取结果 $totalB = $factory->getResultAll('rebate8', $numB, $priceB); $this->display('B', 'rebate8', $numB, $priceB, $totalB);
// 购买数量 $numC = 10; // 单价 $priceC = 100; // 返利策略获取结果 $totalC = $factory->getResultAll('return300to100', $numC, $priceC); $this->display('C', 'return300to100', $numC, $priceC, $totalC); }
/** * 打印 * * @param string $name 商品名 * @param string $type 类型 * @param int $num 数量 * @param double $price 单价 * @return double */ public function display($name, $type, $num, $price, $total){ echo date('Y-m-d H:i:s') . ",$name,[$type],num:$num,price:$price,total:$total<br>"; } }
/** * 程序入口 */ function start(){ $client = new Client(); $client->main(); }
start();
?>
打印结果: 2018-10-09 11:17:30,A,[normal],num:10,price:100,total:1000 2018-10-09 11:17:30,B,[rebate8],num:5,price:100,total:400 2018-10-09 11:17:30,C,[return300to100],num:10,price:100,total:700
|
请发表评论