首页 > 语言 > PHP > 正文

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

2024-05-04 23:59:45
字体:
来源:转载
供稿:网友

本文实例讲述了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教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选