php策略模式替换if else

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");
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容