解决什么样的问题
自定义按键
代码讲解
紧密耦合关系
public class NBAGameHandler { public void pushA(){ System.out.println("投篮"); } public void pushB(){ System.out.println("封盖"); } public void pushC(){ System.out.println("抢断"); } public void pushD(){ System.out.println("挡拆"); } }
以物件来代表实际行动。也就是说方法的内容抽象到一个对象中。把按键和动作解耦。
public interface Command { public abstract void excute(); }
public class NBAGameHandler { private Command[] command = new Command[4]; public void setA(Command command){ this.command[0]=command; } public void setB(Command command){ this.command[1]=command; } public void setC(Command command){ this.command[2]=command; } public void setD(Command command){ this.command[3]=command; } public void pushA(){ command[0].excute(); } public void pushB(){ command[1].excute(); } public void pushC(){ command[2].excute(); } public void pushD(){ command[3].excute(); } }
public static void main(String[] args) { NBAGameHandler handler = new NBAGameHandler(); handler.setA(new ShootCommand()); handler.setB(new BlockCommand()); handler.setC(new PickAndRollCommand()); handler.setD(new StealCommand()); handler.pushA(); handler.pushB(); handler.pushC(); handler.pushD(); }
public class BlockCommand implements Command{ //真实项目往往在这里会封装一个对象,完成具体的业务!!!而不会简单的打印一句话哦。 @Override public void excute() { System.out.println("封盖"); } }