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

相关文章

php实现的click captcha点击验证码类实例

php实现的click captcha点击验证码类实例

本文实例讲述了php实现的click captcha点击验证码类及其用法,是非常实用的功能。分享给大家供大家参考之用。具体如下: 一、需求: 现在常用的表单验证码大部分都是要用户输入为主...

php绘制一条直线的方法

本文实例讲述了php绘制一条直线的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:<?php //1、创建画布 $im = imagecreatetru...

采集邮箱的php代码(抓取网页中的邮箱地址)

复制代码 代码如下: <?php $url='//www.jb51.net'; //这个网页里绝对含有邮件地址。 $content=file_get_contents($url);...

php中注册器模式类用法实例分析

本文实例讲述了php中注册器模式类用法。分享给大家供大家参考,具体如下: 注册器读写类 Registry.class.php <?php /** * 注册器读写类...

Windows上php5.6操作mongodb数据库示例【配置、连接、获取实例】

Windows上php5.6操作mongodb数据库示例【配置、连接、获取实例】

本文实例讲述了Windows上php5.6操作mongodb数据库的方法。分享给大家供大家参考,具体如下: 一、配置 针对不同线程安全、VC版本的 PHP 发行版,可从 PECL 获取到...