如果您需要有兩種算法在運行時可以互換,那麼您應該查看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