Mega Code Archive

 
Categories / Java / Design Pattern
 

Command pattern

/* Software Architecture Design Patterns in Java by Partha Kuchana  Auerbach Publications */ import java.util.HashMap; public class CommandTest {   public static void main(String[] args) {     //Add an item to the CD category     //create Receiver objects     Item CD = new Item("A Beautiful Mind");     Category catCD = new Category("CD");     //create the command object     CommandInterface command = new AddCommand(CD, catCD);     //create the invoker     ItemManager manager = new ItemManager();     //configure the invoker     //with the command object     manager.setCommand(command);     manager.process();     //Add an item to the CD category     CD = new Item("Duet");     catCD = new Category("CD");     command = new AddCommand(CD, catCD);     manager.setCommand(command);     manager.process();     //Add an item to the New Releases category     CD = new Item("Duet");     catCD = new Category("New Releases");     command = new AddCommand(CD, catCD);     manager.setCommand(command);     manager.process();     //Delete an item from the New Releases category     command = new DeleteCommand(CD, catCD);     manager.setCommand(command);     manager.process();   } } class ItemManager {   CommandInterface command;   public void setCommand(CommandInterface c) {     command = c;   }   public void process() {     command.execute();   } } class Item {   private HashMap categories;   private String desc;   public Item(String s) {     desc = s;     categories = new HashMap();   }   public String getDesc() {     return desc;   }   public void add(Category cat) {     categories.put(cat.getDesc(), cat);   }   public void delete(Category cat) {     categories.remove(cat.getDesc());   } } class DeleteCommand implements CommandInterface {   Item item;   Category cat;   public DeleteCommand(Item i, Category c) {     item = i;     cat = c;   }   public void execute() {     item.delete(cat);     cat.delete(item);   } } interface CommandInterface {   public void execute(); } class Category {   private HashMap items;   private String desc;   public Category(String s) {     desc = s;     items = new HashMap();   }   public String getDesc() {     return desc;   }   public void add(Item i) {     items.put(i.getDesc(), i);     System.out.println("Item '" + i.getDesc() + "' has been added to the '"         + getDesc() + "' Category ");   }   public void delete(Item i) {     items.remove(i.getDesc());     System.out.println("Item '" + i.getDesc()         + "' has been deleted from the '" + getDesc() + "' Category ");   } } class AddCommand implements CommandInterface {   Item item;   Category cat;   public AddCommand(Item i, Category c) {     item = i;     cat = c;   }   public void execute() {     item.add(cat);     cat.add(item);   } }