Saturday, November 13, 2010

..........Command Pattern

When two objects communicate, often one object is sending a command to the other object to perform a particular function.The most common way to accomplish this is for the first object (the "issuer") to hold a reference to the second (the "recipient"). The issuer executes a specific method on the recipient to send the command.
But what if the issuer is not aware of, or does not care who the recipient is? That is, the issuer simply wants to abstractly issue the command?
The Command design pattern encapsulates the concept of the command into an object. The issuer holds a reference to the command object rather than to the recipient. The issuer sends the command to the command object by executing a specific method on it. The command object is then responsible for dispatching the command to a specific recipient to get the job done.

Example. 1. When you use web browser there is mthod ExecCommand, When we call that method to execute various command like copy,color,find etc. It send a command to the COM class to execute those methods.
2. To use delegates and event in any program is an example of Command Pattern

Examlpe:-

public class Sender
{
public delegate void Done(int iValue);
public event Done OnDone ;

public void DoIt()
{
if(OnDone != null)
OnDone(10);
}
}


public class Receiver
{
priavte Sender m_objSender = null;

public void Action()
{
m_objSender.OnDone += new Done(OnDone);
}

private void OnDone(int iValue)
{
MessageBox.Show(“Work has been done for “ + iValue);
}
}

No comments:

Followers

Link