Sunday, June 3, 2012

Behavioral Patterns - 2.Command Pattern

There could be a need of a programming model which would associate some workflow or operations to an object.

 So that, the task of performing the operation/workflow is delegated to the object.

They can be triggered by a request, wrapped by an external object. We term those objects as Command Objects.

Following are the terminologies most frequently used in Command pattern.

Invoker:- Triggers a command on an object
Receiver:- Receives a request to execute a command.
Client:- Initializes the command and gets the work done.


The workflow that will happen during the executing of a command as follows,
1. Client will initialize and prepare a command with a receiver.
2. Client will initialize the invoker with the command prepared.
3. Client requests the invoker to execute a command
4. Invoker triggers the command
5. The command indentifies the receiver and fires the request over it


For example, we consider a Student/Teacher scenario in a particular class.
The teacher will command the students to either stand/sit. The students will act accordingly to the command issued by the teacher.

Here, Student is the Receiver Object, teacher is an Invoker and Stand/Sit will be a Command object.

The client will prepare the receiver(Student) and associate the command(stand/sit).Then, the invoker(Teacher) will be initialized with the same command(stand/sit) object.

After that, the client requests the invoker(Teacher) to execute the command(Stand/sit). The invoker(Teacher) triggers the command(Stand/Sit). The command identifies the receiver(Student) and gets executed.

The following class diagram explains the above description,


Code Snippet:

Client:

Student student=new Student();
Command standCommand=new Stand(student);
  //Associate the Receiver to the command
Command sitCommand=new Sit(student); //Associate the Receiver to the command


Teacher teacher=new Teacher(standCommand,sitCommand); //Initialize the Invoker with the command

teacher.sitDown(); //Request the Invoker to trigger the Command
teacher.standUp(); //Request the Invoker to trigger the Command

Invoker:

public Teacher(Command standCommand, Command sitCommand) { //Initialize the Invoker with the command
  this.standCommand = standCommand;
  this.sitCommand = sitCommand;
 }


public String standUp(){
  return standCommand.execute();
//Trigger the Command
 }

 public String sitDown(){
  return sitCommand.execute();
//Trigger the Command
 }

Command:

class Sit implements Command{
 private Student student;  
// Command with the Receiver
...
}

public String execute() {
  return student.sit(); //Command Execution
 }

No comments:

Post a Comment