[review]Design Pattern:Command

weixin_30588675發表於2020-04-05

Command

Encapsulate an request into the object. The command holds the receiver, the invoker holds the command.

encapsulate the details, show the interface to the client. the client does not know the exact implemetation .

The client only cares about his request and tells the invoker what his request is, the invoker creates an appropriate command according to the client's request and executes the command.

The command holds the approriate receiver. the receiver's action is executed, the things are done.

Actually this pattern also decouples the appearance from the implemetation. So called DP is nothing but OOD, exactly the experience about how the BIG GUYS use the OOD.

IMO, every software designer and programmer should know all the DP even you don't use some of them. after that you got more than the DP itself. One who learns the PD should compare them together.

I do like this pattern very much. I got more than the pattern itself.

A small demo here to show the above:

namespace Command
{
public class Receiver
{
public void Action()
{
Console.WriteLine("Execute Action");
}
}

public abstract class Command
{
protected Receiver receiver;

public Command(Receiver receiver)
{
this.receiver = receiver;
}

public abstract void Execute();
}

public class ConcreteCommand : Command
{
public ConcreteCommand(Receiver receiver) : base(receiver) { }
public override void Execute()
{
receiver.Action();
}
}

public class Invoker
{
private Command command;

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

public void ExecuteCommand()
{
this.command.Execute();
}
}

class Client
{
static void Main(string[] args)
{
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);

Invoker i = new Invoker();
i.SetCommand(c);
i.ExecuteCommand();
}
}
}



轉載於:https://www.cnblogs.com/sanjia/archive/2011/12/06/2278613.html

相關文章