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
相关文章推荐
- Thinkphp简单无限级分类
- 一、Yii框架学习之单选框
- php接收表单中有大数组存在时的问题
- php in_array的性能问题,附加调试方法
- php过滤函数封装
- Laravel PHPExcel 使用
- php防注入函数隐患
- Yii 如何在ActiveRecord自动化记录时间戳
- PHP mysql事务问题实例分析
- Yii中CDbCriteria常用总结
- PHP获取路径和目录方法总结
- php中strtr和str_replace的坑
- php自带过滤函数
- php中如何获取文件的正确路径
- 【初探PHP】安装PHP环境
- phpstorm破解码
- php读取指定目录文件夹下所有文件名
- php实现快速排序
- PHP获取文件扩展名的方法
- php之isset empty is_null的区别