您的位置:首页 > 编程语言 > PHP开发

php 策略模式实例

2016-01-18 15:33 621 查看
比如说购物车系统,在给商品计算总价的时候,普通会员肯定是商品单价乘以数量,但是对中级会员提供8者折扣,对高级会员提供7折折扣,这种场景就可以使用策略模式实现:

<?php
/**
* 策略模式实例
*
* @tutorial http://blog.csdn.net/wzy_1988/article/details/9167943 * @author <http://www.phpddt.com>
*/
//抽象策略角色《为接口或者抽象类,给具体策略类继承》
interface Strategy
{
public function computePrice($price);
}

//具体策略角色-普通会员策略类
class GenernalMember implements Strategy
{
public function computePrice($price)
{
return $price;
}
}

//具体策略角色-中级会员策略类
class MiddleMember implements Strategy
{
public function computePrice($price)
{
return $price * 0.8;
}
}

//具体策略角色-高级会员策略类
class HignMember implements Strategy
{
public function computePrice($price)
{
return $price * 0.7;
}
}

//环境角色实现类
class Price
{
//具体策略对象
private $strategyInstance;

//构造函数
public function __construct($instance)
{
$this->strategyInstance = $instance;
}

public function compute($price)
{
return $this->strategyInstance->computePrice($price);
}
}

//客户端使用
$p = new Price(new HignMember());

$totalPrice = $p->compute(100);

echo $totalPrice; //70
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: