假设Receiver是能干很多家务的执行者,比如扫地,做饭,交水电费等等。
public class Receiver
{
//Action1和Action2是做家务
public void Action1()
{
Console.WriteLine("扫地");
}
public void Action2()
{
Console.WriteLine("洗衣服");
}
//Action3和Action4是去交费
public void Action3()
{
Console.WriteLine("交水费");
}
public void Action4()
{
Console.WriteLine("交电费");
}
}
如果直接对他行命令,比如做家务,或者交费,这需要对类进行如下的修改,通过传递给doit一个参数,来命令具体动作。
public class Receiver
{
//Action1和Action2是做家务
public void Action1()
{
Console.WriteLine("扫地");
}
public void Action2()
{
Console.WriteLine("洗衣服");
}
//Action3和Action4是去交费
public void Action3()
{
Console.WriteLine("交水费");
}
public void Action4()
{
Console.WriteLine("交电费");
}
public void doit(int type)
{
if(type == 1) //做家务
{
Action1();
Action2();
}
if(type == 2) //去交费
{
Action3();
Action4();
}
}
}
但是这样存在一个问题,如果想命令他扫地和交水费,则需要修改类内部的if条件,当条件非常复杂时,这样的修改会变得非常不灵活。
而用command设计模式,将Receiver通过命令Command包装后,让Invoker调用,实现了命令的发起者Invoker和命令的执行者Receiver通过Command隔离开,提供了更多的灵活性。用Command设计模式实现如下:
//受信者
//接收命令做相应的处理。
public class Receiver
{
//Action1和Action2是做家务
public void Action1()
{
Console.WriteLine("扫地");
}
public void Action2()
{
Console.WriteLine("洗衣服");
}
//Action3和Action4是去交费
public void Action3()
{
Console.WriteLine("交水费");
}
public void Action4()
{
Console.WriteLine("交电费");
}
}
//抽象的命令类
public abstract class Command
{
protected Receiver res;
//将Receiver在构造函数中设置好
public Command(Receiver res)
{
this.res = res;
}
//Invoker中调用
public abstract void Execute();
}
//命令类(做家务)
public class ConcreteCommand_Task : Command
{
public ConcreteCommand_Task(Receiver res)
: base(res)
{
}
public override void Execute()
{
this.res.Action1();
this.res.Action2();
}
}
//命令类(去交费)
public class ConcreteCommand_TaskPay : Command
{
public ConcreteCommand_TaskPay(Receiver res)
: base(res)
{
}
public override void Execute()
{
this.res.Action3();
this.res.Action4();
}
}
//命令执行者
public class Invoker
{
private Command com;
//通过属性设置命令
public Command SetCommand
{
set { this.com = value; }
}
//让命令对象去执行命令
public void ExecuteCommand()
{
com.Execute();
}
}
class Class1
{
static void Main(string[] args)
{
//受信者(命令实际执行者)
Receiver res = new Receiver();
//实际的命令对象
//家务命令
ConcreteCommand_Task task = new ConcreteCommand_Task(res);
//交费命令
ConcreteCommand_TaskPay pay = new ConcreteCommand_TaskPay(res);
//命令者
Invoker invoker = new Invoker();
//命令者执行设置的命令
invoker.SetCommand = task;
invoker.ExecuteCommand();
invoker.SetCommand = pay;
invoker.ExecuteCommand();
}
}
}
没有评论:
发表评论