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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

PHP关联数组的10个操作技巧

什么是数组? 在使用 PHP 进行开发的过程中,或早或晚,您会需要创建许多相似的变量。 无需很多相似的变量,你可以把数据作为元素存储在数组中。 数组中的元素都有自己的 ID,因此可以方便...

Uncaught exception com_exception with message Failed to create COM object

Uncaught exception com_exception with message Failed to create COM object

在PHP中调用IE使用如下代码: 复制代码 代码如下: browser = new COM("InternetExplorer.Application"); 无法正常调用,直接报错:...

php的4种常见运行方式

SAPI:Server Application Programming Interface服务端应用编程端口。他就是php与其他应用交互的接口,php脚本要执行有很多中方式,通过web服...

PHP排序算法之冒泡排序(Bubble Sort)实现方法详解

本文实例讲述了PHP排序算法之冒泡排序(Bubble Sort)实现方法。分享给大家供大家参考,具体如下: 基本思想: 冒泡排序是一种交换排序,它的基本思想是:两两比较相邻记录的关键字,...

隐性调用php程序的方法

调用方法:<script language = "javascript" src = "count.php"></script> count.php源码:复制代码...