2

我正在尝试创建一个 StandardCard 类,该类将枚举用于西装和数字。我有代码,因为它目前在下面。

我的问题是,将卡片添加到卡片组的 Driver 类应该可以访问枚举。最近阅读了设计模式,我觉得我应该有一个 StandardCardEnums 类,并在 StandardCard 类中创建该类的一个对象以增加模块化。这是要走的路吗?感觉很笨拙,因为我需要做类似的事情

StandardCardEnum myEnums = new StandardCardEnum;
private StandardCardEnum.Suit suit;
etc.....

我当前的代码如下,我看到的问题是 1) 枚举在卡片类中是硬编码的,重复肯定会发生 2) Driver 类需要了解枚举以填充卡片组中的卡片,因此违反对象封装。

任何有更多经验的人都可以为我指出一个好的标准来开始适用于这些类型的情况吗?我正试图从编程转向软件开发。我希望能够创建一个模块化的纸牌游戏框架,让我能够以最少的努力添加不同的纸牌游戏,甚至是套牌组合和纸牌类型。

public class StandardCard extends Card
{
public enum Suit {CLUBS, DIAMONDS, HEARTS , SPADES };
public enum Number {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};

private Suit suit;
private Number number;

public StandardCard(StandardCard.Suit suit, StandardCard.Number number)
{
    this.suit = suit;
    this.number = number;
}

public StandardCard()
{
}

public Suit getSuit()
{
    return suit;
}

public Number getNumber()
{
    return number;
}

public void setSuit(Suit s)
{
    this.suit = s;
}

public void setNumber(Number n)
{
    this.number = n;
}
}
4

2 回答 2

2

将枚举作为顶级类放入它们自己的文件中。

于 2013-02-08T00:31:04.747 回答
1

You should rather make your enums static:

public static enum Suit {CLUBS, DIAMONDS, HEARTS , SPADES };
public static enum Number {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};

This way you can access them as StandardCard.Suit.CLUBS from anywhere in your code (e.g. from Driver), but they're still encapsulated into StandardCard - they have no meaning outside this world.

于 2013-02-08T00:51:00.583 回答