您的位置:首页 > 其它

三、命令模式Commond(行为型模式)

2016-04-15 17:36 239 查看
命令模式将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化:对请求排队或记录请求日志,以及支持可撤销的操作。

package commond;

import java.util.ArrayList;

import java.util.List;

publicclass CommondTest {

}

class MM {

String name;

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

publicvoid order(Boy b){

Command c=new Shopping();

b.addCommand(c);

c=new Hug();

b.addCommand(c);

b.executeCommands();

}

}

class Boy {

String name;

List<Command> commands=new ArrayList<Command>();

public String getName() {

returnname;

}

publicvoid executeCommands() {

for(Command c:commands){

c.execute();

}

}

publicvoid addCommand(Command c) {

commands.add(c);
}

publicvoid setName(String name) {

this.name = name;
}

publicvoid doSomething() {

}
}

abstractclass Command{

publicabstractvoid execute();

publicabstractvoid unDo();

}

class Shopping extends Command{

@Override

publicvoid execute() {

System.out.println("去购物");

}

@Override

publicvoid unDo() {
System.out.println("回家");
}

}

class Hug extends Command{

@Override

publicvoid execute() {
System.out.println("抱抱");
}

@Override

publicvoid unDo() {
System.out.println("走人");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: