gpt4 book ai didi

c# - 对于具有不同行为的多个接口(interface)使用哪种设计模式

转载 作者:行者123 更新时间:2023-12-01 14:11:19 25 4
gpt4 key购买 nike

我有一个像这样的命令界面,

public interface ICommand{
public abstract Object execute(List<Inputs> inputs);
}

现在我有一个用于其他类型的复杂执行的命令,所以我想出了新的命令界面

public interface IComplexCommand {
public abstract Object execute(ComplexObjects obj);
}

我从属性文件中调用命令,这是在 CommandFactory 的静态初始化程序 block 内完成的。我的工厂调用方法如下所示。

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.

现在我遇到一个问题,比如当我收到命令时,我不想根据接口(interface)键入命令,但我希望在运行时理解它,

任何人都可以帮我更好地设计这个吗?我尝试用谷歌搜索,但无法得到任何正确的答案,因为问题非常具体。

最佳答案

我建议不要去任何命令工厂。命令模式实际上可以让您参数化您的请求对象。因此,您可以为简单和复杂的命令场景创建不同类型的命令对象,然后您可以根据从属性文件中检索的命令类型来执行它们。这就是我将按照命令模式执行的操作,看看它是否有帮助:

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();
}
}

输出:

在这里进行简单的操作在这里进行复杂的操作

关于c# - 对于具有不同行为的多个接口(interface)使用哪种设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18508761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com