Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ActionHandler {
- public void doSomething(String message) throws Exception {
- ActionObject actionObj = null;
- if (message.equals("dog")) {
- // ActionObjectDog implements ActionObject
- actionObj = new ActionObjectDog();
- }
- else if (message.equals("cat")) {
- // ActionObjectCat implements ActionObject
- actionObj = new ActionObjectCat();
- }
- else {
- throw new Exception("Action " + message + " not implemented.");
- }
- actionObj.run();
- }
- }
- @Inject private Provider<ActionObject> actionObjectProvider;
- class Module extends AbstractModule {
- @Override protected void configure() {
- MapBinder.newMapBinder(binder(), String.class, ActionObject.class)
- .addBinding("dog").to(ActionObjectDog.class);
- MapBinder.newMapBinder(binder(), String.class, ActionObject.class)
- .addBinding("cat").to(ActionObjectCat.class);
- }
- }
- class ActionHandler {
- private final Map<String, ActionObject> mappings;
- @Inject ActionHandler(Map<String, ActionObject> mappings) {
- this.mappings = mappings;
- }
- public void doSomething(String message) {
- Preconditions.checkNotNull(mappings.get(message), "No action for '" + message + "'")
- .run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement