如果您需要有两种算法在运行时可以互换,那么您应该查看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.
}
}
所以,现在你已经定义了一个通用的接口为你的命令,这意味着它们可以像这样被引用:
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;
}
}
}
T他的手段,你现在有产生这些类的更灵活的方式,你可以按如下方式使用这个类:
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.
编辑回应
我的问题是,为什么定义不同的接口?为什么不喜欢:
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 */
}
}
你不应该开始使用设计模式的目标。你应该设计得很好 - 图案会变得明显。 – Oded
哦。和模式不是相互排斥的。您可以同时使用多个模式。 – Oded
我已经用我的design.clean更新了这个问题,并从不同的界面返回,所以我怎样才能互换? – vkshibu