策略模式如何运作? [英] How does the Strategy Pattern work?
问题描述
$ p
How does it work, what is it used for and when should one use it?
推荐答案
我们来解释一下策略模式简单的方法:
Let's explain the strategy pattern the easy way:
您有一个类 Car()
,方法 run )
,所以你以伪语言这样使用:
You have a class Car()
with a method run()
, so you use it this way in a pseudo language:
mycar = new Car()
mycar.run()
现在,您可能需要更改<$ c $当程序正在执行时,c> run()行为。例如,您可能需要模拟电机故障或在视频游戏中使用boost按钮。
Now, you may want to change the run()
behavior on the fly, while the program is executing. For example, you might want to simulate a motor failure or the use of a "boost" button in a video game.
有几种方法可以进行此模拟:使用条件语句和标志变量是一种方法。策略模式是另一个:它将 run()
方法的行为委托给一个子类:
There are several ways to do this simulation: using conditional statements and a flag variable is one way. The strategy pattern is another: it delegates the behavior of the run()
method to a subclass:
Class Car()
{
this.motor = new Motor(this)
// passing "this" is important for the motor so it knows what it is running
method run()
{
this.motor.run()
}
method changeMotor(motor)
{
this.motor = motor
}
}
如果你想改变汽车的行为,你可以改变电机。 (在一个程序中,在现实生活中更容易,对吗?;-))
If you want to change the car's behavior, you can just change the motor. (Easier in a program then in real life, right? ;-) )
如果你有很多复杂的状态,这是非常有用的:你可以改变和维护他们更容易。
It's very useful if you have a lot of complex states: you can change and maintain them much more easily.
这篇关于策略模式如何运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!