命令模式由接受者,命令,控制器组成。目的是为了把发出命令的责任和执行分开,委派给不同对象。
每个命令都有个操作,请求方发出个命令请求控制器操作,控制方收到命令并执行操作。
public class Light {
public void lightOn() {
System. out .println(" light is on" );
}
}
public interface Commond {
void excute();
}
public class LightOnCommond implements Commond {
private Light light ;
public LightOnCommond(Light light){
this .light = light;
}
public void excute() {
light.lightOn();
}
}
public class RemoteControl {
private Commond commond ;
public void setCommond(Commond commond) {
this .commond = commond;
}
public void buttonPress() {
commond.excute();
}
}
public class Client {
public static void main(String[] args) {
Light light = new Light();
Commond commond = new LightOnCommond(light);
RemoteControl control = new RemoteControl();
control.setCommond(commond);
control.buttonPress();
}
}