PHP设计模式 六
策略模式
策略模式是一种行为型设计模式,它定义了一系列算法(策略),将每个算法封装起来,使它们可以互相替换。
策略模式让算法的变化独立于使用算法的客户端,从而避免大量使用 if-else 或 switch-case 判断。
抽象策接口
具体策略类1
具体策略类2
……
调用类
调用类中可设置具体抽象类,设置方法的参数类型是抽象策略类。
逻辑实现时调用具体抽象类。
应用范围
适合一个操作可使用多种方法操作,比如支付使用支付宝或者微信,数据连接使用mysql或者redis等。
| |
|---|
| 支付宝、微信、银行卡、PayPal 等多种支付策略 |
| |
| |
| |
| |
| |
| |
代码实现
抽象策略接口
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")