如何在策略模式中使用外部类?
我为扑克牌局历史文件解析器(PHP 或 Java 代码)实现了一个策略模式。我有一个问题,为几种策略使用的类和对象创建一个干净的 OOP 方式。
在现实生活中:
我有一个类游戏,其中有手
class Hand
{
... // attributes for all strategies
... // (in fact : attributes that define the "core" of a Hand)
}
class Game
{
Hand hands[];
}
一个策略将创建一个对象游戏和手
class StrategyA implements IStrategy // strategy pattern
{
Game game;
function Parse()
{
game = new Game();
...
}
}
这个策略将需要游戏和每只手的特定属性 我无法将这些属性放入手牌或游戏中,尽管它们仅被一种策略使用,而不被其他策略使用。 我的问题是:最好的 OOP 方式是什么?为策略创建特定的类?
class HandForStrategyA extends Hand
{
Int x; // useful only in the strategy A context
}
class StrategyA
{
Game game;
HandForStrategyA hands[];
}
这似乎是显而易见的答案,但我仍然想知道是否有更好的方法。此外,我在语义上有一个问题:我应该给我的类起什么样的名称(HandFor...感觉很糟糕!)。 我是一个老派程序员,非常程序化,我浪费了很多时间来思考“干净的”OOP!
I implemented a strategy pattern for a poker hand history file parser (PHP or Java code). I have a problem to create a clean OOP way for classes and objects used by the several strategies.
In real life :
I have a class Game which has Hand(s)
class Hand
{
... // attributes for all strategies
... // (in fact : attributes that define the "core" of a Hand)
}
class Game
{
Hand hands[];
}
One strategy will create an object Game and the Hands
class StrategyA implements IStrategy // strategy pattern
{
Game game;
function Parse()
{
game = new Game();
...
}
}
And this strategy will need specific attributes for game and each hands
I cannot put theses attributes into Hand or Game though there only used by one strategy and not the others.
My question is : what is the best OOP way ? Create specific classes for the strategy ?
class HandForStrategyA extends Hand
{
Int x; // useful only in the strategy A context
}
class StrategyA
{
Game game;
HandForStrategyA hands[];
}
It seems the obvious answer but I am still wondering if there any better ways. Furthermore, I have a problem with semantic : what kind of name should I give to my classes (HandFor... feels bad !).
I am an old-school programmer, very procedural, and I lose so much time to think about "clean" OOP !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您自己回答了这个问题“并且此策略将需要游戏和手牌的特定属性”。您编写一个策略,属性将成为该策略的一部分。
You answered the question yourself "And this strategy will need specific attributes for game and hands". You write a a strategy and the attributes are going to be part of this strategy.