行为性模式-命令模式 (Command)

1.简介

我们想实现的是,只需要输入一个字符串式的指令,就可以执行相应的逻辑,而不用if else什么来判断。
PHP Cli命令的设计就会用到这个模式。

2.代码实现

我们来实现一个电视机开关的指令:

//命令接口
interface Command{
    public function excecute();
}
//开电视指令
class turnOnTVCommand extends Command{
    private $controller;
    public function __construct(Controller $controller){
        $this->controller = $controller;
    }
    public function excecute(){
        $this->controller->turnOnTV();
    }
}
//关电视指令
class turnOffTVCommand extends Command{
    private $controller;
    public function __construct(Controller $controller){
        $this->controller = $controller;
    }
    public function excecute(){
        $this->controller->turnOffTV();
    }
}
//指令库控制器(储存所有具体执行逻辑)
class Controller {
    public function turnOnTV(){
        echo '打开电视';
    }
    public function turnOffTV(){
        echo '关闭电视';
    }
}

3.使用

$command_string = 'turnOnTV'.'Command';
$command = new $command_string(new Controller());
$command->excecute();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值