策略模式

将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式

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

抽象策略角色

<?php
/**
 * 策略模式实例
 *
 */
//抽象策略角色《为接口或者抽象类,给具体策略类继承》
interface Strategy
{
  public function computePrice($price);
}

具体策略角色-普通会员策略类

<?php
//具体策略角色-普通会员策略类
class GenernalMember implements Strategy
{
  public function computePrice($price)
  {
    return $price;
  }
}

具体策略角色-中级会员策略类

<?php
//具体策略角色-中级会员策略类
class MiddleMember implements Strategy
{
  public function computePrice($price)
  {
    return $price * 0.8;
  }
}

具体策略角色-高级会员策略类

<?php
//具体策略角色-高级会员策略类
class HignMember implements Strategy
{
  public function computePrice($price)
  {
    return $price * 0.7;
  }
}

环境角色实现类

<?php
//环境角色实现类
class Price
{
  //具体策略对象
  private $strategyInstance;
  //构造函数
  public function __construct($instance)
  {
    $this->strategyInstance = $instance;
  }
  public function compute($price)
  {
    return $this->strategyInstance->computePrice($price);
  }
}

客户端

<?php

//客户端使用
$p = new Price(new HignMember());
$totalPrice = $p->compute(100);
echo $totalPrice; //70

本文由 一切随风 创作,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论