设计模式—命令模式

命令模式将请求封装到一个对象当中,命令模式是对命令的封装。

命令模式把发出命令的责任和执行命令的责任分割开,A负责发出命令,B负责接收命令并执行。

以一个女孩命令男孩做事情为例:

1.命令接口

package com.bjsxt.dp.command;

public abstract class Command {
    public abstract void execute();
    public abstract void unDo();
}

2.具体命令

package com.bjsxt.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");
    }

}

3.具体命令

package com.bjsxt.dp.command;

public class ShoppingCommand extends Command {

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

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

}

4.女孩下命令

package com.bjsxt.dp.command;

public class MM {

    public void order(Boy b) {
        Command c1 = new ShoppingCommand();
        b.addCommand(c1);
        Command c2 = new HugCommand();
        b.addCommand(c2);
        b.executeCommands();
    }
}

5.男孩执行命令

package com.bjsxt.dp.command;

import java.util.ArrayList;
import java.util.List;

public class Boy {
    private List<Command> commands = new ArrayList<Command>();

    public void addCommand(Command c1) {
        this.commands.add(c1);
    }

    public void executeCommands() {
        for(Command c : commands) {
            c.execute();
        }
    }
    
    public void undoCommands() {
        //
    }
    
}

 

posted @ 2017-05-18 21:54  开拖拉机的蜡笔小新  阅读(193)  评论(0编辑  收藏  举报