命令者模式
来源:互联网 发布:网络挂号,厦门中医院 编辑:程序博客网 时间:2024/05/17 22:34
-
- public abstract class Command {
- public abstract void execute();
-
- public abstract void unDo();
- }
- public class ShopingCommand extends Command{
- @Override
- public void execute() {
- System.out.println("逛街");
- }
-
- @Override
- public void unDo() {
- System.out.println("不逛街,回家");
- }
-
- }
- public class HugCommand extends Command{
-
- @Override
- public void execute() {
- System.out.println("拥抱");
- }
-
- @Override
- public void unDo() {
- System.out.println("展开双臂");
- }
-
- }
- public class Boy {
- List<Command> commands=new ArrayList<Command>();
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- public void addCommand(Command m){
- commands.add(m);
- }
- public void dosomething(){
- }
- public void executeCommand(){
- for(Command m : commands){
- m.execute();
- }
- }
- }
- public class MM {
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- private String name;
-
- public void order(Boy body){
- Boy b=new Boy();
- Command com1=new ShopingCommand();
- Command com2=new HugCommand();
- b.addCommand(com1);
- b.addCommand(com2);
- b.executeCommand();
- }
- }
- public class Test {
- public static void main(String[] args) {
- MM mm=new MM();
- mm.setName("美女");
- Boy boy=new Boy();
- boy.setName("屌丝");
- mm.order(boy);
- }
-
-
-
-
-
- }