1 16 package com.buchuki.ensmer.input.command; 17 18 import java.util.*; 19 import com.buchuki.ensmer.input.event.*; 20 import groovy.lang.Closure; 21 22 36 public class CommandMap { 37 38 50 public void addCommand(Object owner, Command command, EnsmerInputEvent event) { 51 removeCommand(owner, event); List<CommandEvent> ownerList = owners.get(owner); 53 if (ownerList == null) { 54 ownerList = new ArrayList<CommandEvent>(); 55 owners.put(owner, ownerList); 56 } 57 CommandEvent cmdevt = new CommandEvent(command, event); 58 ownerList.add(cmdevt); 59 } 60 61 72 public void addCommand(Object owner, Closure command, EnsmerInputEvent event) { 73 addCommand(owner, new ClosureCommand(command), event); 74 } 75 76 86 public Command getCommand(Object owner, EnsmerInputEvent event) { 87 List<CommandEvent> ownerList = owners.get(owner); 88 if (ownerList == null) { 89 return null; 90 } 91 for (CommandEvent cmd: ownerList) { 92 if (cmd.getEvent().equals(event)) { 93 return cmd.getCommand(); 94 } 95 } 96 return null; 97 } 98 99 107 public Command removeCommand(Object owner, EnsmerInputEvent event) { 108 List <CommandEvent> ownerList = owners.get(owner); 109 if (ownerList == null) { 110 return null; 111 } 112 Command command = null; 113 Iterator<CommandEvent> i = ownerList.iterator(); 114 while (i.hasNext()) { 115 CommandEvent cmd = i.next(); 116 if (cmd.getEvent().equals(event)) { 117 if (command == null) { command = cmd.getCommand(); 119 } 120 i.remove(); 121 } 122 } 123 return command; 124 } 125 126 131 public void removeAllCommands(Object owner) { 132 owners.remove(owner); 133 } 134 135 146 public boolean interpretEvent(Object owner, EnsmerInputEvent event) { 147 Command cmd = getCommand(owner, event); 148 if (cmd != null) { 149 return cmd.execute(event); 150 } 151 return false; 152 } 153 154 157 private Map<Object , List<CommandEvent>> owners = 158 new HashMap<Object , List<CommandEvent>>(); 159 160 167 private class CommandEvent { 168 169 175 public CommandEvent(Command command, EnsmerInputEvent event) { 176 this.command = command; 177 this.event = event; 178 } 179 180 185 public Command getCommand() { 186 return command; 187 } 188 189 194 public EnsmerInputEvent getEvent() { 195 return event; 196 } 197 198 201 private Command command; 202 203 206 private EnsmerInputEvent event; 207 } 208 } 209 210 217 class ClosureCommand implements Command { 218 221 private Closure closure; 222 223 227 public ClosureCommand(Closure closure) { 228 this.closure = closure; 229 } 230 231 235 public boolean execute(EnsmerInputEvent event) { 236 return (Boolean ) closure.call(event); 237 } 238 } 239 | Popular Tags |