2013-07-14 122 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

相关问题