PHP实现的策略模式简单示例

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP实现的策略模式。分享给大家供大家参考,具体如下:

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

<?php
/**
 * 策略模式实例
 *
 */
//抽象策略角色《为接口或者抽象类,给具体策略类继承》
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
?>

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

关于file_get_contents返回为空或函数不可用的解决方案

如果你使用file_get_contents获取远程文件内容返回为空或提示该函数不可用,也许本文能帮到你! 使用file_get_contents和fopen必须空间开启allow_ur...

php中使用接口实现工厂设计模式的代码

接口在php只能起到约束类的定义作用,虽不像c#/java那么直观,但基于oop的封装要求,使用接口可以提高程序的可扩展性,如实现代理设计模式。 复制代码 代码如下: <?php...

php email邮箱正则

1.验证email: < ?php    if (ereg("/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[...

php中this关键字用法分析

本文实例讲述了php中this关键字用法。分享给大家供大家参考,具体如下: 下面定义了一个Cart类 <?php class Cart { var $items;...

thinkphp 多表 事务详解

如下所示:复制代码 代码如下:function makeAcquire($nUsers,$nAwards)    {    &...