Guest User

Untitled

a guest
Jun 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class ChainDemo {
  4.  
  5. static interface Command {
  6. void execute(Map<String, Object> ctx);
  7. }
  8.  
  9. static class Chain {
  10. private List<Command> commands = new ArrayList<Command>();
  11.  
  12. public void addCommand(Command cmd) {
  13. commands.add(cmd);
  14. }
  15.  
  16. public void execute() {
  17. Map<String, Object> ctx = new HashMap<String, Object>();
  18.  
  19. for (Command cmd : commands) {
  20. cmd.execute(ctx);
  21. }
  22. }
  23.  
  24. }
  25.  
  26. public static void main(String[] args) {
  27. Chain chain = new Chain();
  28. chain.addCommand(new Command() {
  29. public void execute(Map<String, Object> ctx) {
  30. // Perform some calc here
  31. ctx.put("result1", 1234);
  32. }
  33. });
  34. chain.addCommand(new Command() {
  35. public void execute(Map<String, Object> ctx) {
  36. int res = (Integer) ctx.get("result1");
  37. ctx.put("result2", res * 2);
  38. }
  39. });
  40. chain.addCommand(new Command() {
  41. public void execute(Map<String, Object> ctx) {
  42. System.err.println("Results: ");
  43. for (String key : ctx.keySet()) {
  44. System.err.println("\t" + key + ": " + ctx.get(key));
  45. }
  46. }
  47. });
  48. chain.execute();
  49. }
  50. }
Add Comment
Please, Sign In to add comment