我是第一次尝试使用命令模式,并通过它创建一个命令工厂,我正在遵循 pluralsight.com 类(class)的指导,他在该类(class)中为工厂实现了一个接口(interface),其中包括一个 MakeCommand 方法。
现在我的问题来自于他只是传递一个字符串数组作为此方法的参数(他是一个命令行应用程序),但是我的命令将使用各种类型的各种参数,我的计划是使用这些命令来存储对模型的更新,因此如果应用程序无法连接到服务,这些命令将在连接恢复时排队等待。
对于通用接口(interface),这一直是我的症结所在,我该如何处理大量可能的参数?
我的第一个想法是传递模型本身,使用带有命令类型(删除、更新等)的简单字符串参数,但是由于我的模型没有任何公共(public)基类或接口(interface),所以我遇到了类似的问题.
我是不是漏掉了一些基本的东西?
编辑:要求提供我的问题示例。
我有一个 CommandFactory 接口(interface)
public interface ICommandFactory
{
string CommandName { get; }
string Description { get; }
ICommand MakeCommand( ..arguments.. )
}
我有一些简单的模型,例如(纯示例)
public class Model1
{
public string Name {get;set;}
public int Age {get;set;}
}
public class Model2
{
public DateTime Time {get;set;}
public double Price {get;set}
}
如果我想创建一个命令,例如更新模型 1,我想知道接口(interface)的 MakeCommand 应该是什么样子,我不能做 MakeCommand(string cmdType, Model1 model) 因为我有多个不同的模型共享没有共同的基类/接口(interface)
最佳答案
您似乎希望各个模型定义它们的更新方式。在那种情况下,您不能将函数/操作从模型传递到 MakeCommand 吗?
public class Model
{
public string Name {get;set;}
public int Age {get;set;}
public void UpdateModel() {...}
}
public interface ICommandFactory
{
string CommandName { get; }
string Description { get; }
ICommand MakeCommand(Action<Model>);
ICommand MakeCommandFunc(Func<Model, bool>);
}
public class Command : ICommand
{
Action<Model> _action;
Command(Action<Model> action)
{
_action = action;
}
Execute()
{
_action();
}
}
编辑: 根据要求,使用公共(public)接口(interface)类对所有类进行建模
public interface IModel
{
void UpdateModel();
}
public class Model1 : IModel
{
public string Name {get;set;}
public int Age {get;set;}
// implement updating of the model
public void UpdateModel() {...do model update...}
}
public class Model2 : IModel
{
public DateTime Time {get;set;}
public double Price {get;set}
// 'dummy' implement updating of the model if this model does not supports updating
public void UpdateModel() { // do nothing or throw NotImplementedException(); }
}
public interface ICommandFactory
{
string CommandName { get; }
string Description { get; }
ICommand MakeCommand( IModel model );
}
关于c# - 工厂方法 - 未知参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32074101/