命令模式将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。用户程序在使用的时候,只与该命令对象打交道,而不用与一类对象打交道,降低了耦合性,提高了程序设计的灵活性。
我们还是那数据库操作为例
public
class DBInstance
{
public void ExecuteNonQuery()
{
}
public void ExecuteDataset()
{
}
}
public class SqlInstance : DBInstance
{
public void ExecuteNonQuery()
{
Console.WriteLine( " this is a SqlInstance ");
}
}
public class OracleInstance : DBInstance
{
public void ExecuteNonQuery()
{
Console.WriteLine( " this is a OracleInstance ");
}
}
public interface Command
{
void execute();
}
public class SqlCommand : Command
{
SqlInstance sqlinstance;
public SqlCommand(SqlInstance sqlins)
{
this.sqlinstance = sqlins;
}
public void execute()
{
sqlinstance.ExecuteNonQuery();
}
}
public class OracleCommand : Command
{
OracleInstance Oracleinstance;
public OracleCommand(OracleInstance Oracleins)
{
this.Oracleinstance = Oracleins;
}
public void execute()
{
Oracleinstance.ExecuteNonQuery();
}
}
public class DBControl
{
Command[] commands;
public DBControl()
{
commands = new Command[ 2];
}
public void setCommand( int index,Command comm)
{
commands[index] = comm;
}
public void control( int index)
{
commands[index].execute();
}
}
{
public void ExecuteNonQuery()
{
}
public void ExecuteDataset()
{
}
}
public class SqlInstance : DBInstance
{
public void ExecuteNonQuery()
{
Console.WriteLine( " this is a SqlInstance ");
}
}
public class OracleInstance : DBInstance
{
public void ExecuteNonQuery()
{
Console.WriteLine( " this is a OracleInstance ");
}
}
public interface Command
{
void execute();
}
public class SqlCommand : Command
{
SqlInstance sqlinstance;
public SqlCommand(SqlInstance sqlins)
{
this.sqlinstance = sqlins;
}
public void execute()
{
sqlinstance.ExecuteNonQuery();
}
}
public class OracleCommand : Command
{
OracleInstance Oracleinstance;
public OracleCommand(OracleInstance Oracleins)
{
this.Oracleinstance = Oracleins;
}
public void execute()
{
Oracleinstance.ExecuteNonQuery();
}
}
public class DBControl
{
Command[] commands;
public DBControl()
{
commands = new Command[ 2];
}
public void setCommand( int index,Command comm)
{
commands[index] = comm;
}
public void control( int index)
{
commands[index].execute();
}
}
测试下命令模式
DBControl dc =
new DBControl();
SqlInstance si = new SqlInstance();
SqlCommand sc = new SqlCommand(si);
OracleInstance oi = new OracleInstance();
OracleCommand oc = new OracleCommand(oi);
dc.setCommand( 0, sc);
dc.setCommand( 1, oc);
dc.control( 0);
dc.control( 1);
SqlInstance si = new SqlInstance();
SqlCommand sc = new SqlCommand(si);
OracleInstance oi = new OracleInstance();
OracleCommand oc = new OracleCommand(oi);
dc.setCommand( 0, sc);
dc.setCommand( 1, oc);
dc.control( 0);
dc.control( 1);
总结:有的同学可能会问接收者有必要存在吗?为何命令对象不知想实现execute()方法的细节。一般来说,我们设计命令对象,它或许只需要调用一个接收者的一个行为。然而有许多命令对象会实现许多逻辑,直接完成一个请求。当然你可以设计更全面的命令对象,只是这样一来,调用者和接收者之间的解耦程度会再度降低。实际项目中命令可以将运算快打包(一个接收者一组动作),然后将他们传来传去,就像是普通对象一样。所以在日程安排、线程池、事务队列中命令模式的使用也是比较广泛的,