我正在编写一个与划船有关的程序,并且正在创建一个名为“BoatType”的不可变类,以表示存在的船的不同“类型”。由于有许多类型需要唯一说明,因此这变得复杂。
BoatType应该具有以下内容:
在赛艇世界中,仅存在这些字段的某些组合,这使情况更加复杂。我希望我的程序可以轻松枚举对这些标准类型的访问,而不必创建新的BoatType对象。这些是:
双桨8
短桨4
双桨2
短桨1
扫8口固定
扫8 STARBOARD COXED
扫4口固定
扫4口无毒
扫4 STARBOARD COXED
扫描4 STARBOARD UNOXED
SWEEP 2 PORT COXED
SWEEP 2端口无毒
扫描2 STARBOARD COXED
SWEEP 2 STARBOARD未氧化
目前,这是我用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(而不是ScullBoatType)上定义两个布尔字段“isPort”和“isCoxed”。像这样:
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...