java 命令模式

UML:

java 命令模式_第1张图片
1.png

定义:

将某个请求(开机,关机,换台)封装成一个对象(TurnOnCommand,TurnOffCommand,ChangeChannelCommand),从而可用不同的请求实现客户端的参数化( Control control = new Control(on, off, changechannel))

本质:

将发出请求的对象(client)请求的真正执行者(mytv)解耦。

角色:

Command: 命令接口,声明执行操作。
ConcreateCommand:实现commmand 命令持有真正的执行者。将执行者与命令绑定。TurnOffCommand
Client:创建命令设定执行者。Client
Invoker:执行命令请求。Control
Receiver:命令的执行者。mytv
(1)命令真正的执行者

public class MyTV {
    public int channel = 0;

    public void turnOff() {
        System.out.println("mytv is turn off!!");
    }

    public void turnOn() {
        System.out.println("mytv is turn on!!");
    }

    public void changeChannel(int channel) {
        this.channel = channel;
        System.out.println("now tv chaannel is " + channel + "!!");
    }
}

(2)命令接口

public interface Command {
    public void execute();
}

(3)命令实现类

public class implements Command {
    private MyTV myTV;

    public TurnOffCommand(MyTV myTV) {
        this.myTV = myTV;
    }

    @Override
    public void execute() {
        myTV.turnOff();
    }
}
public class TurnOnCommand implements Command {
    private MyTV myTV;

    public TurnOnCommand(MyTV myTV) {
        this.myTV = myTV;
    }

    @Override
    public void execute() {
        myTV.turnOn();
    }
}
public class ChangeChannelCommand implements Command {
    private MyTV myTV;
    private int  channel;

    public ChangeChannelCommand(MyTV myTV, int channel) {
        this.myTV = myTV;
        this.channel = channel;
    }

    @Override
    public void execute() {
        myTV.changeChannel(channel);
    }
}

(3)控制器

public class Control {
    public Command oncommand, offcommand, changecommand;

    public Control(Command oncommand, Command offcommand, Command changecommand) {
        this.oncommand = oncommand;
        this.offcommand = offcommand;
        this.changecommand = changecommand;
    }

    public void turnOn() {
        this.oncommand.execute();

    }

    public void turnOff() {
        this.offcommand.execute();

    }

    public void changeChannel() {
        this.changecommand.execute();
    }
   }

(4)测试类

public class Client {
    public static void main(String[] args) {
        //接受者
        MyTV myTV = new MyTV();
        //开机命令
        Command on = new TurnOnCommand(myTV);
        //关机命令
        Command off = new TurnOffCommand(myTV);
        //换台
        Command changechannel = new ChangeChannelCommand(myTV, 9);
        //命令控制对象
        Control control = new Control(on, off, changechannel);
        control.turnOn();
        control.turnOff();
        control.changeChannel();

    }
}

你可能感兴趣的:(java 命令模式)