php开发技巧

php策略模式替换if else

2023-11-13  本文已影响0人  顶尖少爷

app.php文件 if条件语句

function dmeo($type_name=""){
    if ($type_name=="wx"){
        echo "send wx";
    }elseif ($type_name=="sms"){
        echo "send sms";

    }elseif ($type_name=="email"){
        echo "send email";
    }
}
dmeo("sms");

策略模式改造

wx.php

class wx
{
    public function  send(){
        echo "send wx";
    }
}

email.php

class email
{
    public function send(){
        echo "send email";
    }
}

sms.php

class sms
{

    public function  send(){
        echo "send sms";
    }
}

存储上面策略的工厂 Factory.php

class Factory
{

    public $product = [];

    public function get($type){
        return $this->product[$type] ;
    }

    public function  register($type){
        $class = ucfirst($type);
        $this->product[$type] = new $class;
    }
}

操作 action

require_once("email.php");
require_once("sms.php");
require_once("wx.php");
require_once("Factory.php");

class Controller {
    public $types = ["wx","sms","email"];
    public $factory =null;
    public function __construct(){
        //生成所有策略对象
        $this->factory = new Factory();
        foreach($this->types as $type){
            $this->factory->register($type);
        }
    }


   //根据传递的type参数 , 选择使用哪一个策略
    public function  doAction($type=""){
        $notic = $this->factory->get($type);
        $notic->send();
    }
}

$req = new Controller();
$req->doAction("email");
上一篇 下一篇

猜你喜欢

热点阅读