命令模式

来源:互联网 发布:论文流程图画图软件 编辑:程序博客网 时间:2024/06/05 22:41

这里写图片描述

/** * 士兵 * @author Administrator * */public class Soldier {    private  String attach;    private  String back;    public String getAttach() {        return attach;    }    public void setAttach(String attach) {        this.attach = attach;    }    public String getBack() {        return back;    }    public void setBack(String back) {        this.back = back;    }/** * 军队 * 具体执行攻打任务 * @author Administrator * */public class Army {    private Soldier soldier;    public Army(Soldier soldier) {        super();        this.soldier = soldier;    }    public void attack()    {        soldier.setAttach("攻击  齐国");        System.out.println("攻击  齐国");    }    public void back()    {        soldier.setBack("前方大事不妙,赶紧撤退");        System.out.println("前方大事不妙,赶紧撤退");    }    public void undo()    {        soldier.setBack("原路撤退");        System.out.println("原路撤退");    }}/** * 命令 圣旨 * @author Administrator * */public interface Command {    void excute();    void back();}//真实命令public class AttachCommand implements Command {    private Army army;    public AttachCommand(Army army) {        this.army = army;    }    @Override    public void excute() {        army.attack();    }    @Override    public void back() {        army.back();    }}//真实命令public class UndoCommand   implements Command {    private Army army;    public UndoCommand(Army army) {        this.army = army;    }    @Override    public void excute() {        army.undo();    }    @Override    public void back() {        army.back();    }}/** * 将军 * @author Administrator * */public class General {    private Command undoCommand;    private Command attackCommand;    public General()    {        //构建士兵        Soldier soldier=new Soldier();        //建立军队        Army army=new Army(soldier);        undoCommand=new UndoCommand(army);        attackCommand =new AttachCommand(army);    }    /**     * 皇帝调用大臣攻击方法     */    public void attach()    {        attackCommand.excute();    }    public  void  undo()    {        undoCommand.back();    }}//皇帝public class Emperor {    public static void main(String[] args) {        General general=new General();        general.attach();        general.undo();        /**         * 不仅仅做隔离         */         }}
原创粉丝点击