我看过 this explanation on Wikipedia ,特别是 C++ 示例,并且无法识别仅定义 3 个类、创建实例并调用它们与该示例之间的区别。我所看到的只是将另外两个类放入该过程中,并且看不到哪里会有好处。现在我确定我错过了一些明显的东西(树木的木材) - 有人可以用一个明确的现实世界的例子来解释它吗?
到目前为止,我可以从答案中得出什么,在我看来,这只是一种更复杂的方法:
have an abstract class: MoveAlong with a virtual method: DoIt()
have class Car inherit from MoveAlong,
implementing DoIt() { ..start-car-and-drive..}
have class HorseCart inherit from MoveAlong,
implementing DoIt() { ..hit-horse..}
have class Bicycle inherit from MoveAlong,
implementing DoIt() { ..pedal..}
now I can call any function taking MoveAlong as parm
passing any of the three classes and call DoIt
Isn't this what Strategy intents? (just simpler?)
[编辑更新]
我上面提到的函数被另一个类替换,其中 MoveAlong 将是根据在这个新类中实现的算法根据需要设置的属性。 (类似于接受的答案中展示的内容。)
[编辑更新] 结论
策略模式有它的用途,但我是 KISS 的坚定信徒,并且倾向于更直接和更少混淆的技术。主要是因为我想传递易于维护的代码(并且'因为我很可能是必须进行更改的人!)。
最佳答案
关键是将算法分成可以在运行时插入的类。例如,假设您有一个包含时钟的应用程序。有许多不同的方法可以绘制时钟,但在大多数情况下,底层功能是相同的。这样就可以创建时钟显示界面了:
class IClockDisplay
{
public:
virtual void Display( int hour, int minute, int second ) = 0;
};
然后你有你的时钟类,它连接到一个计时器并每秒更新一次时钟显示。所以你会有类似的东西:
class Clock
{
protected:
IClockDisplay* mDisplay;
int mHour;
int mMinute;
int mSecond;
public:
Clock( IClockDisplay* display )
{
mDisplay = display;
}
void Start(); // initiate the timer
void OnTimer()
{
mDisplay->Display( mHour, mMinute, mSecond );
}
void ChangeDisplay( IClockDisplay* display )
{
mDisplay = display;
}
};
然后在运行时用适当的显示类实例化你的时钟。也就是说,您可以让 ClockDisplayDigital、ClockDisplayAnalog、ClockDisplayMartian 都实现 IClockDisplay 接口(interface)。
因此,您以后可以通过创建一个新类来添加任何类型的新时钟显示,而不必弄乱您的 Clock 类,也不必重写可能难以维护和调试的方法。
关于design-patterns - 使用策略模式的好处在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/171776/