实施战略模式

发布于 2024-07-21 00:27:48 字数 48 浏览 3 评论 0原文

在实现策略模式时,将决定使用哪种策略的代码放在哪里? 一些示例伪代码会有所帮助。

When implementing the Strategy Pattern, where does one put the code that determines which strategy to use? Some sample pseudo-code would help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌能量女王 2024-07-28 00:27:48

该决定由使用策略模式的对象的客户端做出。 举例来说,您有一个角色对象,它根据角色当时拥有的武器使用不同的攻击方式来攻击其他角色。 当游戏玩家选择角色将使用哪种武器时,将决定使用哪种策略。

因此,角色和武器(示例中策略模式的两个主要组件)都不会决定使用哪种策略,而是由使用角色和武器的代码来决定。 通过简单地创建一个新的武器对象(例如 RayGunWeapon)并将其“给予”您的角色,就可以改变角色的行为。

尽管您可以编写显式选择策略的代码,但我认为这种模式的真正价值在于它可以在运行时完成。

That decision is taken by the client of the Objects that use the Strategy Pattern. Lets say for instance that you have a Character Object that attacks other characters using a different attack style based on which Weapon the Character posesses at the time. The decision of which Strategy to use would then be made by the player of the game when she chooses which weapon the character will use.

So neither the Character nor the Weapon (the two main components of the Strategy Pattern in the example) decides which Strategy to use, rather the code that makes use of Characters and Weapons do so. By simply creating a new Weapon object (say a RayGunWeapon) and "giving" it to your Character changes the Character's behaviour.

Even though you could write code that explicitly chooses a Strategy, I think the real value of this pattern is that it can be done at run time.

嘿看小鸭子会跑 2024-07-28 00:27:48

您选择如何实现它将决定代码在哪里,以及它是编译还是在运行时完成。

例如,如果您使用依赖注入 (DI),那么您通常可以通过更改 xml 文件在运行时注入不同的策略。

如果您使用 AOP,那么它将在运行时或编译时进行,具体取决于您如何编写方面。

如果您使用 Spring Framework,那么这与使用 DI 类似,并且可以像在不同的类中进行连接一样简单。

如果您使用服务定位器,那么它可能就像交换不同的 DLL 一样简单。

基本上有很多方法可以实现策略模式,我只是列出了一些,所以它所依赖的评论是非常正确的。

How you choose to implent it will determine where the code is, and whether it is compiled in or done at runtime.

For example, if you use Dependency Injection (DI) then you can often inject a different strategy at runtime by changing an xml file.

If you use AOP then it would be at runtime or compile time, depending on how you wrote the aspect.

If you use Spring Framework then that is similar to using DI, and can be as easy as wiring in a different class.

If you use a service locator then it may be as simple as swapping in a different DLL.

Basically there are many ways to implement a strategy pattern, I just listed a few, so the comment that it depends is very correct.

纵性 2024-07-28 00:27:48

这完全取决于您何时决定采取哪种策略。 有时可以在创建时解决策略,有时则是运行时的事情。 简单的答案取决于。

It all depends when you resolve which strategy to take. Sometimes one can resolve the strategy at create time, other times its a runtime thing. The simple answer it depends.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文