Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, August 10, 2009

Command Pattern In Java

Hi Friends,

Today I would like to show a program for command patterns.

* Client.java

/**
* Creates a ConcreteCommand object and specifies its receiver.
*/

public class Client
{
public Command setup()
{
Command command = new ConcreteCommand();
Receiver receiver = new ConcreteReceiver();
command.setReceiver( receiver );

// We return the command so that the Invoker may use it.

return command;
}
}

* Command.java

/**
* Declares an interface for executing an operation.
*/

public interface Command
{
void setReceiver( Receiver receiver );
Receiver getReceiver();
void execute();
}

* ConcreteCommand.java

/**
* Defines a binding between a Receiver object and an
* action. Implements Execute by invoking the corresponding
* operation on Receiver.
*/

public class ConcreteCommand implements Command
{
private Receiver receiver;

public void setReceiver( Receiver receiver )
{
this.receiver = receiver;
}

public Receiver getReceiver()
{
return receiver;
}

public void execute()
{
receiver.action();
}
}

* ConcreteReceiver

/**
* Implementation of the Receiver interface.
*/

public class ConcreteReceiver implements Receiver
{
public void action()
{
}
}

* Receiver.java

/**
* Knows how to perform the operations associated with
* carrying out a request. Any class may serve as a Receiver.
*/

public interface Receiver
{
void action();
}

* Test.java

/**
* Test driver for the pattern.
*/

public class Test
{
public static void main( String arg[] )
{
try
{
Client client = new Client();
Command command = client.setup();
command.execute();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}

So friends, Hope you found it useful. Please give your valuable feedback.

No comments: