策略模式是如何工作的? [英] How does the Strategy Pattern work?

查看:18
本文介绍了策略模式是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是如何工作的,它的用途是什么以及何时应该使用它?

How does it work, what is it used for and when should one use it?

推荐答案

让我们简单地解释一下策略模式:

Let's explain the strategy pattern the easy way:

您有一个带有方法 run() 的类 Car(),因此您可以在伪语言中以这种方式使用它:

You have a class Car() with a method run(), so you use it this way in a pseudo language:

mycar = new Car()
mycar.run()

现在,您可能希望在程序执行时动态更改 run() 行为.例如,您可能想要模拟电机故障或在视频游戏中使用加速"按钮.

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 another class:

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 than 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆