对我来说,策略模式只不过是使用对象组合来允许在一个类中使用一堆不同的策略并在运行时互换。在您的情况下,如果您希望 Antenna 类根据输入值在运行时更改其行为(算法),则可以使用策略模式。如果是这种情况,在 Antenna 类中,您有一个指向 AlgorithmInterface 的实例变量,它由 4 个类派生:AlgoATransmit、AlgoBTransmit、AlgoAReceive 和 AlgoBReceive。这 4 个类中的每一个都将定义真正的算法。然后,您需要一个客户端类来检查输入值类型,并将天线设置为使用适当的算法。
虽然我看不到如何应用命令模式,但您的问题可能也是模板方法模式的一个很好的案例,您可以将它与策略一起使用。你可以做的是有一个抽象类,我们称之为 AbstractAlgorithm,它有一个“模板方法”,通过调用单独的函数来定义算法的公共流程。这些函数将在子类中被覆盖,例如 AlgorithmA、AlgorithmB。
天线的方向可以通过使用模板方法中的“钩子”来解决。钩子基本上是在子类中可选覆盖的函数。
这是一个简单的示例代码。Antenna利用Object Composition and Strategy,有一个变量指向抽象算法,由2个算法派生而来。这样,算法的大纲可以在一个地方指定,每个具体步骤都在子类中定义。希望它有所帮助,我希望我能正确理解您的问题。
class Antenna {
private AbstractAlgorithm algo;
void SetAlgo(AbstractAlgorithm newAlgo) {
algo = newAlgo;
}
}
class AbstractAlgorithm {
//this is the template method
void runAlgo() {
step1(); //step1 and step2 are two common steps for both algorithms
step2();
if (isMatrixValue())
step3(); //a hook, only AlgoB will override it.
if (isTransmitting())
step4(); //a hook, use for transmit
else if (isReceiving())
step5(); //a hook, use for receive
}
abstract void step1();
abstract void step2();
boolean isMatrixValue() {
return false; //default value, to not run step3
}
}
class AlgorithmA {
void step1() {
//some implementation
}
void step2() {
//some implementation
}
//use the default false value for isMatrixValue(), not to run step3
}
class AlgorithmB {
void step1() {
//some implementation
}
void step2() {
//some implementation
}
void step3() {
//some implementation
}
boolean isMatrixValue() {
return true; //return true and override step3
}
}