我有一个这样的命令界面,
public interface ICommand{
public abstract Object execute(List<Inputs> inputs);
}
现在我有一个其他类型的复杂执行命令,所以我想出了新的命令接口
public interface IComplexCommand {
public abstract Object execute(ComplexObjects obj);
}
我调用属性文件中的命令,该命令在CommandFactory的静态初始化程序块内完成。我的Invoke方法看起来像这样。
ICommand cmd= CommandFactory.getInstance().getCommand("LoopElements");
// loopElements is the key in properties file to load my com.test.my.LoopElements
// to call execute of IComplex command it will not work because I have to typecase
// this I want to avoid.
现在我遇到了一个问题,例如当我获得命令时我不想根据接口对命令进行类型化操作,但我想在运行时理解它,
任何人都可以帮助我更好地设计这个。我试图谷歌,但我无法得到任何正确的答案,因为这个问题非常具体。
答案 0 :(得分:1)
我建议不去任何指挥工厂。命令模式实际上允许您参数化您的请求对象。因此,您可以为简单而复杂的命令方案创建不同类型的命令对象,然后您可以根据从属性文件中检索的命令类型执行它们。 这是我将按照命令模式执行的操作,看看它是否有帮助:
public interface IOperations
{
void PerformOperations();
}
public class EasyOperations : IOperations
{
public void PerformOperations()
{
Console.WriteLine("Do easy operations here");
}
}
public class ComplexOperations : IOperations
{
public void PerformOperations()
{
Console.WriteLine("Do complex operations here");
}
}
public interface ICommand
{
void Execute();
}
public class EasyCommand : ICommand
{
IOperations opn;
public EasyCommand(IOperations opn)
{
this.opn=opn;
}
public void Execute()
{
opn.PerformOperations();
}
}
public class ComplexCommand : ICommand
{
IOperations opn;
public ComplexCommand(IOperations opn)
{
this.opn=opn;
}
public void Execute()
{
opn.PerformOperations();
}
}
public class OperationsPerformer
{
IDictionary<string, ICommand> commands = new Dictionary<string, ICommand>();
public OperationsPerformer()
{
commands.Add("easy", new EasyCommand(new EasyOperations()));
commands.Add("complex",new ComplexCommand(new ComplexOperations()));
}
public void perform(string key)
{
if (commands[key] != null)
{
ICommand command = commands[key];
command.Execute();
}
}
}
public class Client
{
public static void Main(String[] args)
{
OperationsPerformer performer = new OperationsPerformer();
performer.perform("easy");
performer.perform("complex");
Console.ReadKey();
}
}
输出:
在这里轻松操作 在这里做复杂的操作
答案 1 :(得分:0)
你可以这样设计:
public interface ICommand
{
public Object execute();
}
public class Command : ICommand
{
List<Input> inputs;
public void setInputs(List<Input> inputs)
{
this.inputs = inputs;
}
public Object execute()
{
// do something
}
}
public class ComplexCommand : ICommand
{
ComplexObjects inputs;
public void setInputs(ComplexObjects inputs)
{
this.inputs = inputs;
}
public Object execute()
{
// do something
}
}
这两个类的对象可以被视为ICommand
个对象,因此客户端代码可以调用execute()
,而不需要关心接口背后的具体类。