java – 用于表示比枚举更复杂但不是一个类的字段的良好数据结构是什么?

我正在编写一个涉及划船的程序,我正在创建一个名为“BoatType”的不可变类来表示船只的不同“类型”.这变得越来越复杂,因为有许多类型需要独特的描述.

BoatType应具有以下内容:

> SCULL或SWEEP类型
>一个数字,即适合乘船的人数
> PORT或STARBOARD类型,但仅限于第一种类型是SWEEP
>表示COXED或UNCOXED的布尔值,通常仅用于SWEEP

由于在划船世界中仅存在这些场的某些组合,因此这进一步复杂化.我希望我的程序能够轻松枚举这些标准类型,而无需创建新的BoatType对象.这些是完整的:

SCULL 8
SCULL 4
SCULL 2
SCULL 1
SWEEP 8 PORT COXED
SWEEP 8 STARBOARD COXED
SWEEP 4 PORT COXED
SWEEP 4 PORT UNCOXED
SWEEP 4 STARBOARD COXED
SWEEP 4 STARBOARD UNCOXED
SWEEP 2 PORT COXED
SWEEP 2 PORT UNCOXED
SWEEP 2 STARBOARD COXED
SWEEP 2 STARBOARD UNCOXED

目前这是我用Java编写的类:

public class BoatType
{
public enum RiggerType{SCULL, SWEEP_PORT, SWEEP_STARBOARD}

private int numSeats;

private RiggerType riggerType;

public boolean coxswain = true;

public BoatType(RiggerType type, int seats, boolean coxed)
{
    numSeats = seats;
    riggerType = type;
    coxswain = coxed;
}
}

在其他地方列举标准类型:

    public static final BoatType 
    SCULL_OCTUPLE = new BoatType(RiggerType.SCULL, 8, false),
    SCULL_QUAD = new BoatType(RiggerType.SCULL, 4, false),
    SCULL_DOUBLE = new BoatType(RiggerType.SCULL, 2, false),
    SCULL_SINGLE = new BoatType(RiggerType.SCULL, 1, false),
    SWEEP_PORT_EIGHT_COXED  = new BoatType(RiggerType.SWEEP_PORT, 8, true),
    SWEEP_STARBOARD_EIGHT_COXED = new BoatType(RiggerType.SWEEP_STARBOARD, 8, true),
    SWEEP_PORT_FOUR_COXED = new BoatType(RiggerType.SWEEP_PORT, 4, true),
    SWEEP_PORT_FOUR_UNCOXED = new BoatType(RiggerType.SWEEP_PORT, 4, false),
    SWEEP_STARBOARD_FOUR_COXED = new BoatType(RiggerType.SWEEP_STARBOARD, 4, true),
    SWEEP_STARBOARD_FOUR_UNCOXED = new BoatType(RiggerType.SWEEP_STARBOARD, 4, false),
    SWEEP_PORT_PAIR_COXED = new BoatType(RiggerType.SWEEP_PORT, 2, true),
    SWEEP_PORT_PAIR_UNCOXED = new BoatType(RiggerType.SWEEP_PORT, 2, false),
    SWEEP_STARBOARD_PAIR_COXED = new BoatType(RiggerType.SWEEP_STARBOARD, 2, true),
    SWEEP_STARBOARD_PAIR_UNCOXED = new BoatType(RiggerType.SWEEP_STARBOARD, 2, false);

这当前看起来相当麻烦,所以我想知道是否有人更好地了解如何表示这一点.枚举是不可能的,因为虽然这些是现有的标准类型,但我不想将其限制为这些组合.

最佳答案
您可以创建BoatType抽象并创建BoatType的两个子类,即ScullBoatType和SweepBoatType.然后,您可以在SweepBoatType上定义两个布尔字段“isPort”和“isCoxed”(但不在ScullBoatType上).像这样:

abstract class BoatType {
    protected int numSeats;

    public BoatType(int numSeats) {
            this.numSeats = numSeats;
    }
}

final class ScullBoatType extends BoatType {
    public ScullBoatType(int numSeats) {
        super(numSeats);
    }
}

final class SweepBoatType extends BoatType {
    private boolean isPort;
    private boolean isCoxed;

    public SweepBoatType(int numSeats, boolean isPort, boolean isCoxed) {
        super(numSeats);
        this.isPort = isPort;
        this.isCoxed = isCoxed;
    }
}

然后可以像这样创建新实例:

BoatType SCULL_OCTUPLE = new ScullBoatType(8);
BoatType SWEEP_PORT_EIGHT_COXED = new SweepBoatType(8, true, true);
// and so on...

转载注明原文:java – 用于表示比枚举更复杂但不是一个类的字段的良好数据结构是什么? - 代码日志