首页 > ASP.net教程

CommandPattern

2016-12-29 18:01:30

/** * 命令模式 * @author TMAC-J * 将调用者和接受者分离 * 可以将一组命令组合在一起,适合很多命令的时候 */public class CommandPattern {    interface Command{    void excute();  }    public class TVReceiver{        public void shift(){      System.out.println("shift");    }        public void turnon(){      System.out.println("turnon");    }        public void Turndown(){      System.out.println("Turndown");    }      }    public class ShiftTV implements Command{    private TVReceiver tv;        public ShiftTV(TVReceiver tv) {      this.tv = tv;    }        @Override    public void excute() {      tv.shift();    }      }    public class TurnonTV implements Command{        private TVReceiver tv;        public TurnonTV(TVReceiver tv) {      this.tv = tv;    }        @Override    public void excute() {      tv.turnon();    }      }  public class Turndown implements Command{        private TVReceiver tv;        public Turndown(TVReceiver tv) {      this.tv = tv;    }        @Override    public void excute() {      tv.Turndown();    }      }    public class Invoker{        private Command shiftTv,turnon,turndown;        public Invoker(Command shiftTv,Command turnonTV,Command turndown) {      this.shiftTv = shiftTv;      this.turnon = turndown;      this.turndown = turndown;    }        public void shift(){      shiftTv.excute();    }    public void turnon(){      turnon.excute();    }        public void turndown(){      turndown.excute();    }  }    public class Client{    public void test(){      TVReceiver tv = new TVReceiver();      Invoker invoker = new Invoker(new ShiftTV(tv), new TurnonTV(tv), new Turndown(tv));      invoker.shift();      invoker.turnon();      invoker.turndown();    }  }    }