当前位置:首页>php>[PHP]设计模式 六 策略模式

[PHP]设计模式 六 策略模式

  • 2026-09-02 19:03:52
[PHP]设计模式 六 策略模式

PHP设计模式 六

策略模式

策略模式是一种行为型设计模式,它定义了一系列算法(策略),将每个算法封装起来,使它们可以互相替换。

策略模式让算法的变化独立于使用算法的客户端,从而避免大量使用 if-else 或 switch-case 判断。

抽象策接口
具体策略类1
具体策略类2
……
调用类

调用类中可设置具体抽象类,设置方法的参数类型是抽象策略类。

逻辑实现时调用具体抽象类。

应用范围

适合一个操作可使用多种方法操作,比如支付使用支付宝或者微信,数据连接使用mysql或者redis等。

场景类型
举例说明
支付方式
支付宝、微信、银行卡、PayPal 等多种支付策略
出行方式
飞机、火车、汽车、步行等路线计算策略
价格计算
会员折扣、满减、秒杀价、无优惠等促销策略
排序算法
冒泡排序、快速排序、归并排序等可动态切换的算法
文件压缩
ZIP、RAR、7z 等压缩格式策略
日志记录
控制台日志、文件日志、数据库日志、远程日志等策略
数据校验
邮箱格式、手机号、身份证、自定义规则校验策略

代码实现

抽象策略接口

interface LogInterface(){
  private $conn;
  public function setLog();
  public function getConfig();
}

具体策略类

redis 处理日志

class RedisLog implement LogInterface{
  private $log;
  public functiongetConfig(){
return config("redis");
  }
  public functionsetLog(){
$config = $this->getConfig();
    //创建日志对象
$this->log = $this->createLog($config);
  }
  public function write($name,$info){
$this->log->set($name,$info);
  }
}

file 处理日志

class FileLog implement LogInterface{
  private $log;
  public functiongetConfig(){
return config("file");
  }
  public functionsetLog(){
$config = $this->getConfig();
    //创建日志对象
$this->log = $this->createLog($config);
  }
  public function write($name,$info){
$this->log->set($name,$info);
  }
}

调用类

class Log{
  protected $log;
  public function __construct( string $type ){
$this->log = $this->getLogClass($type);
  }
  //创建log类
  private function getLogClass($type){
$class = $type."Log";
if(!class_exists($class)){
      throw new \Exception("class ".$class ." not exists");
    }
return new $class();
  }
  public function write($name,$info){
$this->log->set($name,$info);
  }
}

调用

$type = "redis";
$log = new Log($type);
$log->write("test","test1")

扫描识别二维码关注我们获取更多

最新文章

随机文章