螃蟹学PHP设计模式之策略模式

15.策略模式

看到策略模式貌似很高深,不过其实也比较简单。但是螃蟹还是容易和之前学的建造者模式的使用场合弄混淆,这两种设计模式还是很不一样的。先理清一下关系,建造者是原对象不能改变,需要新的对象来进行拓展。策略模式则是对象实现同一个功能的方法可能有多种,但是直接在原对象进行拓展就会很臃肿,这样创建一个策略方法,再把这些同一功能的方法封装成类,由策略方法来决定使用哪个,这样拓展起来就只需要编写新的功能类,而不需要管原对象怎么去实现调用了。

参考项目模块:支付模块

螃蟹觉得支付是个很好的说明例子,因为支付种类的繁多,对地区和重量都有不同规定,使用策略模式就可以比较好的实现支付需求。

订单处理类:Order.class.php

<?php 

class Order{
	public $sn = '';
	public $goods = array();
	protected $_goodsPrice = 0.00;
	protected $_payStrategy;
	
	public function __construct($sn,$goods){
		$this->sn = $sn;
		$this->goods = $goods;			
	}
	
	public function payStrategy($strategyobj){
		$this->_payStrategy = $strategyobj;
	}
	
	public function pay(){
		$this->_payStrategy->pay($this);
	}
	
	public function getGoodsPrice(){
		if(!($this->_goodsPrice)){
			foreach($this->goods as $goods){
				$this->_goodsPrice += $goods['price']*$goods['nums'];
			}
		}
		return $this->_goodsPrice;
	}
	/**
	 * @param number $_goodsPrice
	 */
	public function setGoodsPrice($_goodsPrice) {
		$this->_goodsPrice = $_goodsPrice;
	}

	
}

?>



订单处理里面定义了支付的策略方法来决定使用哪种支付方式。支付宝支付类:Alipay.pay.php

<?php 
require_once('Order.class.php');
//支付宝
class Alipay{
	private static $rate = 0.05;
	public function pay(Order $order){
		$order ->setGoodsPrice(($order->getGoodsPrice())*(1+self::$rate));
		echo '<br>欢迎使用支付宝,您需要支付5%的手续费,订单:'.$order->sn.' 合计支付金额:¥'.$order->getGoodsPrice();
	}
}

?>



银联支付类:Unionpay.pay.php

<?php 
require_once('Order.class.php');
//支付宝
class Unionpay{
	private static $rate = 0.02;
	public function pay(Order $order){
		$order ->setGoodsPrice(($order->getGoodsPrice())*(1+self::$rate));
		echo '<br>欢迎使用银联卡支付,您需要支付2%的手续费,订单:'.$order->sn.' 合计支付金额:¥'.$order->getGoodsPrice();
	}
}

?>



测试类:TestStrategy.php

<?php 

function __autoload($className){
	if(file_exists($className.'.class.php')){
		require_once($className.'.class.php');
	}else{
		require_once($className.'.pay.php');
	}
}

//模拟订单数据
$order_sn = '201408141753AS9BGS';
$order_goods_data = array();
$order_goods_data[0] = array('title'=>'六神花露水','nums'=>1,'price'=>12.90);
$order_goods_data[1] = array('title'=>'七神大宝丸','nums'=>2,'price'=>2.88);
$order_goods_data[2] = array('title'=>'八神补脑液','nums'=>3,'price'=>39.99);

$order2_sn = '2014081478TG5J786';
$order2_goods_data = array();
$order2_goods_data[0] = array('title'=>'六神花露水','nums'=>2,'price'=>12.90);
$order2_goods_data[2] = array('title'=>'八神补脑液','nums'=>1,'price'=>39.99);

$orderobj = new Order($order_sn, $order_goods_data);
//支付宝支付
$orderobj->payStrategy(new Alipay());
$orderobj->pay();

$orderobj2 = new Order($order2_sn, $order2_goods_data);
//银联支付
$orderobj2->payStrategy(new Unionpay());
$orderobj2->pay();
?>



测试结果:

欢迎使用支付宝,您需要支付5%的手续费,订单:201408141753AS9BGS 合计支付金额:¥145.5615
欢迎使用银联卡支付,您需要支付2%的手续费,订单:2014081478TG5J786 合计支付金额:¥67.1058



再需要添加其他的支付方式,只需要再定义支付类即可。策略模式的好处就是可以很方便的拓展对象的同类功能需求,像数据格式导出,验证方式等,都可以使用策略模式来增强程序的拓展性和可维护性。

你可能感兴趣的:(设计模式,PHP,策略模式)