Command mode
Through the command mode, the requested object and the requested object can depend on abstract programming rather than specific classes to achieve decoupling. In addition, the command mode can be revoked because the request is well encapsulated.
package command;interface ICommand{ public void excute(); public void undo();}class Light{ private String mName; public Light(String name){ mName=name; } public void on(){ System.out.println(mName+" on"); } public void off(){ System.out.println(mName+" off"); }}class LightOnCmd implements ICommand{ Light mLight; public LightOnCmd(Light l){ mLight=l; } @Override public void excute() { // TODO Auto-generated method stub mLight.on(); } @Override public void undo() { // TODO Auto-generated method stub mLight.off(); } }class LightOffCmd implements ICommand{ Light mLight; public LightOffCmd(Light l){ mLight=l; } @Override public void excute() { // TODO Auto-generated method stub mLight.off(); } @Override public void undo() { // TODO Auto-generated method stub mLight.on(); } }class LightController{ ICommand mCmd; public void setCommand(ICommand cmd){ mCmd=cmd; } public void press(){ if(mCmd!=null){ mCmd.excute(); } }}public class CommandPattern { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Light light=new Light("Bedroom Light"); LightOnCmd lightOnCmd=new LightOnCmd(light); LightOffCmd lightOffCmd=new LightOffCmd(light); LightController lightController=new LightController(); lightController.setCommand(lightOnCmd); lightController.press(); lightController.setCommand(lightOffCmd); lightController.press(); }}