2013-07-14 134 views
3

我想用設計模式方法創建兩個算法。機器人應清潔並返回到初始位置。我可以在我的算法中使用哪種設計模式?

打掃房間後,我也需要清潔的路徑。

我打算使用命令模式。但有一個疑問,要求說clean和return algorithem應該是可以互換的,並且需要兩個字符串...所以我懷疑Stratagy比Command模式更好嗎?

根據命令模式,我可以將所有執行的命令存儲在List中並找出路徑。但是我仍然懷疑哪種模式最好(兩個以前需要說明)。

請參閱設計,乾淨,從不同的接口返回,所以我認爲這是很難用工廠進行互換......

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圖像連接

+5

你不應該開始使用設計模式的目標。你應該設計得很好 - 圖案會變得明顯。 – Oded

+0

哦。和模式不是相互排斥的。您可以同時使用多個模式。 – Oded

+0

我已經用我的design.clean更新了這個問題,並從不同的界面返回,所以我怎樣才能互換? – vkshibu

回答

0

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

它應該是可互換的,並且第一個算法的結尾應該打印路徑(第二個算法將給出路徑)。因此,我可以執行命令模式,並且我可以將每個命令存儲在列表中也可以找到路徑(第二個度算法)? – vkshibu

+0

我已經用我的design.clean更新了這個問題,並從不同的界面返回,所以我該如何互換? – vkshibu

+0

請看看我的編輯。 – christopher

相關問題