java设计模式-Command模式

时间:2023-11-09 21:45:08

1.背景:                  

站在MM的角度,想命令追求者Boy干什么就干什么,而且将来还可以扩展,怎么做?
2.代码:                  
Command.java:
package com.cy.dp.command;

public abstract class Command {

    public abstract void execute();        //执行命令
public abstract void undo(); //取消执行命令 }

Command的实现类ShoppingCommand:(逛街命令)

package com.cy.dp.command;

public class ShoppingCommand extends Command {

    @Override
public void execute() {
System.out.println("zoo");
} @Override
public void undo() {
System.out.println("undo zoo");
} }

Command的实现类HugCommand:(拥抱命令)

package com.cy.dp.command;

public class HugCommand extends Command{

    @Override
public void execute() {
System.out.println("hug");
} @Override
public void undo() {
System.out.println("open your arms");
} }

Boy.java:

package com.cy.dp.command;

import java.util.ArrayList;
import java.util.List; public class Boy {
private String name;
private List<Command> commands = new ArrayList<Command>();
//private List<Command> doCommands; 装的是已经执行过的command,用于undo public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public void pursue(MM mm){
} public void executeCommands(){
for(Command c : commands){
c.execute();
}
}
public void undoCommands(){
//循环doCommands来undo
//用栈来操作,最后执行的操作先undo
} public void addCommand(Command c){
this.commands.add(c);
} }

MM.java:

package com.cy.dp.command;

public class MM {
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} //MM命令Boy做什么
public void order(Boy b){
Command c1 = new ShoppingCommand();
Command c2 = new HugCommand();
b.addCommand(c1);
b.addCommand(c2);
b.executeCommands();
}
}