码迷,mamicode.com
首页 > 其他好文 > 详细

命令模式

时间:2019-05-28 15:33:57      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:comm   open   etop   span   and   color   command   code   remote   

/**
 * 命令模式:将方法的请求者跟方法的实现者进行分开,常见的例子:遥控器(命令发送者Invoker) 通过按钮(具体的命令Command) 来操作电视机(Receiver 命令接收者或者说是命令实现者)
 * 这样做的话,方法的请求者(遥控器)跟实现者(电视机)就分开了,解耦合了
 *
 *
 */

//创建遥控器(命令发送者Invoker)
public class RemoteControl {
    //具体的命令Command
    private IButton openButton;

    private IButton closeButton;

    public IButton getOpenButton() {
        return openButton;
    }

    public void setOpenButton(IButton openButton) {
        this.openButton = openButton;
    }

    public IButton getCloseButton() {
        return closeButton;
    }

    public void setCloseButton(IButton closeButton) {
        this.closeButton = closeButton;
    }

    public void openTV(){
        openButton.action();
    }

    public void closeTV(){
        closeButton.action();
    }
}
//命令
public interface IButton {
      void action();
}
//关闭命令
public class CloseButton implements IButton {
    private TV tv;

    public CloseButton(TV tv) {
        this.tv = tv;
    }

    @Override
    public void action() {
        tv.close();
    }
}
//开关按钮
public class OpenButton implements IButton {
    //Receiver 命令接收者或者说是命令实现者
    private TV tv;

    public OpenButton(TV tv) {
        this.tv = tv;
    }

    @Override
    public void action() {
        tv.open();
    }
}
//Receiver 命令接收者或者说是命令实现者
public class TV {
    public void open(){
        System.out.println("开电视机");
    }
    public void close(){
        System.out.println("关电视机");
    }
}
public class Test {
    public static void main(String[] args) {

        //创建调用者遥控器
        RemoteControl remoteControl = new RemoteControl();

        //创建接收者TV
        TV tv = new TV();
        //创建开机按钮
        IButton openButton = new OpenButton(tv);
        //创建关机按钮
        IButton closeButton = new CloseButton(tv);
        //绑定按钮
        remoteControl.setCloseButton(closeButton);
        remoteControl.setOpenButton(openButton);

        //开机

        remoteControl.openTV();

        //关机

        remoteControl.closeTV();

    }
}

 

命令模式

标签:comm   open   etop   span   and   color   command   code   remote   

原文地址:https://www.cnblogs.com/yangxiaohui227/p/10937633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!