Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. public class ActionHandler {
  2.  
  3. public void doSomething(String message) throws Exception {
  4.  
  5. ActionObject actionObj = null;
  6.  
  7. if (message.equals("dog")) {
  8. // ActionObjectDog implements ActionObject
  9. actionObj = new ActionObjectDog();
  10. }
  11. else if (message.equals("cat")) {
  12. // ActionObjectCat implements ActionObject
  13. actionObj = new ActionObjectCat();
  14. }
  15. else {
  16. throw new Exception("Action " + message + " not implemented.");
  17. }
  18.  
  19. actionObj.run();
  20. }
  21. }
  22.  
  23. @Inject private Provider<ActionObject> actionObjectProvider;
  24.  
  25. class Module extends AbstractModule {
  26. @Override protected void configure() {
  27. MapBinder.newMapBinder(binder(), String.class, ActionObject.class)
  28. .addBinding("dog").to(ActionObjectDog.class);
  29. MapBinder.newMapBinder(binder(), String.class, ActionObject.class)
  30. .addBinding("cat").to(ActionObjectCat.class);
  31. }
  32. }
  33.  
  34. class ActionHandler {
  35. private final Map<String, ActionObject> mappings;
  36. @Inject ActionHandler(Map<String, ActionObject> mappings) {
  37. this.mappings = mappings;
  38. }
  39.  
  40. public void doSomething(String message) {
  41. Preconditions.checkNotNull(mappings.get(message), "No action for '" + message + "'")
  42. .run();
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement