Skip to content

Instantly share code, notes, and snippets.

@fdb
Created September 19, 2012 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdb/3748294 to your computer and use it in GitHub Desktop.
Save fdb/3748294 to your computer and use it in GitHub Desktop.
Solving the expression problem in Java using maps.
package sandbox;
public interface Command {
}
package sandbox;
public interface Formatter {
public String format(Object o);
}
package sandbox;
public class MoveCommand {
private int x;
private int y;
public MoveCommand(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public Object getY() {
return y;
}
}
package sandbox;
public class MoveCommandFormatter implements Formatter {
@Override
public String format(Object o) {
MoveCommand c = (MoveCommand) o;
return String.format("<MoveCommand %s,%s>", c.getX(), c.getY());
}
}
package sandbox;
import java.util.HashMap;
import java.util.Map;
public class Printer {
private static final Map<Class, Formatter> DEFAULT_FORMATTERS = new HashMap();
static {
DEFAULT_FORMATTERS.put(MoveCommand.class, new MoveCommandFormatter());
DEFAULT_FORMATTERS.put(StopCommand.class, new StopCommandFormatter());
}
private Map<Class, Formatter> formatters;
public Printer() {
this(DEFAULT_FORMATTERS);
}
public Printer(Map<Class, Formatter> formatters) {
this.formatters = formatters;
}
public void print(Object o) {
System.out.println(format(o));
}
public String format(Object o) {
if (o == null) {
return "<null>";
} else if (formatters.containsKey(o.getClass())) {
return formatters.get(o.getClass()).format(o);
} else {
return "<unknown object " + o + ">";
}
}
public static void main(String[] args) {
MoveCommand mc = new MoveCommand(10, 20);
StopCommand sc = new StopCommand();
java.util.Date d = new java.util.Date(1348040520000L);
Printer p = new Printer();
p.print(mc);
p.print(sc);
p.print(d);
}
}
package sandbox;
public class StopCommand implements Command {
}
package sandbox;
public class StopCommandFormatter implements Formatter {
@Override
public String format(Object o) {
StopCommand c = (StopCommand) o;
return String.format("<StopCommand>");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment