Monday, January 12, 2009

Sample of Java Pattern -- Command

Command.java
package command;

public interface Command {
public void execute();
}


ConfirmCommand.java
package command;

public class ConfirmCommand implements Command {

private EmailService emailService;

public ConfirmCommand(){}

public void execute() {
emailService = new EmailService();
emailService.confirmMeeting();
}

}


CancelCommand.java
package command;

public class CancelCommand implements Command {

private EmailService emailService;

public CancelCommand(){}

public void execute() {
emailService = new EmailService();
emailService.cancelMeeting();
}

}


EmailService.java
package command;

public class EmailService {

public EmailService(){}

public void cancelMeeting(){
System.out.println("send cacellation email");
}

public void confirmMeeting(){
System.out.println("send confirmation email");
}

}


Invoker.java
package command;

public class Invoker {
private Command command;

public Invoker(){
}

public void setCommand(Command command){
this.command = command;
}

public void executeCommand(){
this.command.execute();
}
}


CommandTest.java
package command;

public class CommandTest {

public static void main(String[] args) {
CancelCommand cancelCommand = new CancelCommand();
ConfirmCommand confirmCommand = new ConfirmCommand();
Invoker invoker = new Invoker();
invoker.setCommand(confirmCommand);
invoker.executeCommand();
invoker.setCommand(cancelCommand);
invoker.executeCommand();
}

}
you can download the source code .

No comments:

Post a Comment