gpt4 book ai didi

c# - 我可以在我的算法中使用哪种设计模式?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:39 25 4
gpt4 key购买 nike

我想用设计模式方法创建两个算法。机器人应清洁并返回初始位置。

打扫完房间后,我还需要打扫干净的路径。

我打算使用命令模式。但有一个疑问,要求说清除算法和返回算法应该可以互换,并且需要两种算法......所以我怀疑战略是否优于命令模式?

根据命令模式,我可以将所有执行的命令存储在一个列表中并找出路径。但我仍然怀疑哪种模式是最好的(要求说两次前需要)。

请查看设计,清理并从不同的界面返回,所以我认为很难使用工厂来实现互换...

public interface ICleaningAlgorithm {
void Clean(IRobot robot);
}

public interface IReturnAlgorithm {
void Return(IRobot robot);
}
Example classes (without implementation):

public class CleaningAlgorithm : ICleaningAlgorithm {
public void Clean(IRobot robot) {
/* pseudocode from the post */
}
}

public class ReturnAlgorithm {
public void Return(IRobot robot) {
/* some shortest path algorithm */
}
}

enter image description here附设计UML图片

最佳答案

如果您需要两种在运行时可互换的算法,那么您应该研究Factory 模式和Command 模式。正如 Oded 所说,设计模式并不相互排斥。

例如

public interface Command
{
// First, you define a common interface for all commands.
public void execute();
}

public class Command1 implements Command
{
// Implement the execute method.
public void execute()
{
// Run some code in here.
}
}

public class Command2 implements Command
{
// Implement the execute method for the second command.
public void execute()
{
// Run some more code in here.
}
}

所以,现在您已经为您的命令定义了一个通用接口(interface),这意味着它们可以像这样被引用:

Command com = new Command2();
// This is an important property!

现在您将实现您的 Factory 类:

public class CommandFactory
{

public static int ALGO_1 = 1;
public static int ALGO_2 = 2;

public Command getInstance(int discriminator)
{
// Check the value, and if it matches a pre-defined value..
switch(discriminator)
{
case ALGO_1:
return new Command1();
break;
case ALGO_2:
return new Command2();
break;
}
}
}

这意味着您现在可以更灵活地生成这些类,您可以按如下方式使用此类:

CommandFactory factory = new CommandFactory();

Command com = factory.getInstance(CommandFactory.ALGO_1);
// You've just generated algorithm 1.
com.execute();
// And you've just ran the code in algorithm 1.

响应编辑

我的问题是,为什么要定义不同的接口(interface)?为什么不这样:

public interface Algorithm {
void execute(IRobot robot);
}

public class CleaningAlgorithm : Algorithm {
public void execute(IRobot robot) {
/* pseudocode from the post */
}
}

public class ReturnAlgorithm : Algorithm {
public void execute(IRobot robot) {
/* some shortest path algorithm */
}
}

关于c# - 我可以在我的算法中使用哪种设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17637755/

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