1. 为什么需要命令模式?
假设有一个类的方法需要完成某个行为,但是这个行为又不能确定,只能调用的时候才知道使用什么行为。也就是说,行为可能随时都会改变。这个时候,为了拓展性更好,命令模式就能解决这一问题。
2. 什么是命令模式?
专门有一个命令的类,作为参数传给某一个类,命令这个类的方法,完成某一种行为。
3. java代码:
package com.huxin.commandpattern.domain;
public class Person {
private Control control;
public Person(Control control){
this.control = control;
}
public static void test(){
Tv tv = new Tv();
CloseCommand c = new CloseCommand(tv);
Control control = new Control(c);
control.open();
}
public static void main(String[] args) {
test();
}
}
package com.huxin.commandpattern.domain;
public class Control {
private Command command;
public Control(Command c){
this.command = c;
}
public void open(){
command.execute();
}
}
package com.huxin.commandpattern.domain;
public interface Command {
void execute();
}
package com.huxin.commandpattern.domain;
public class OpenCommand implements Command {
private Tv tv;
public OpenCommand(Tv tv){
this.tv = tv;
}
public void execute() {
tv.open();
}
}
package com.huxin.commandpattern.domain;
public class CloseCommand implements Command{
private Tv tv;
public CloseCommand(Tv tv){
this.tv = tv;
}
public void execute() {
tv.close();
}
}
package com.huxin.commandpattern.domain;
public class Tv {
private int currentChanel;
public void open(){
System.out.println("打开");
}
public void close(){
System.out.println("关闭");
}
public void changeChanel(int i){
currentChanel = i;
System.out.println("频道已经改变");
}
}