Tuesday, November 17, 2015

Head First Design Pattern CH6: Command Pattern


in case you see something like this

public void actionPerformed(ActionEvent e)
{
  Object o = e.getSource();
  if (o = fileNewMenuItem)
    doFileNewAction();
  else if (o = fileOpenMenuItem)
    doFileOpenAction();
  else if (o = fileOpenRecentMenuItem)
    doFileOpenRecentAction();
  else if (o = fileSaveMenuItem)
    doFileSaveAction();
  // and more ...
}

then sure there is a problem, as you can see you are checking the instance and then you call an action method, this means that all these instances should implement a single interface which is the Command interface

// the Command Pattern in Java
public interface Command
{
  public void execute();
}

this interface should be implemented by all the types mentioned in actionPerformed

public class FileOpenMenuItem extends JMenuItem implements Command
{
  public void execute()
  {
    // your business logic goes here
  }
}

now simply you can write actionPerformed like this


public void actionPerformed(ActionEvent e)
{
  Command command = (Command)e.getSource();
  command.execute();
}

sure you can extend this pattern to do something more, for example maybe e.getSource() returns a list, you can simple loop over the list and call execute()

also you can add undo() function to the command interface and implement this function.


No comments:

Post a Comment