如果您需要两种在运行时可互换的算法,那么您应该研究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;
}
}
}
这意味着您现在可以更灵活地生成这些类,并且可以按如下方式使用此类:
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 */
}
}