// Methods that set and get the status variable.
}
下面这段代码展示它是如何 work 的:
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
testPz.setStatus(Pizza.PizzaStatus.READY);
assertTrue(testPz.isDeliverable());
}
6.EnumSet and EnumMap
6.1. EnumSet
EnumSet
是一种专门为枚举类型所设计的 Set
类型。
与HashSet
相比,由于使用了内部位向量表示,因此它是特定 Enum
常量集的非常有效且紧凑的表示形式。
它提供了类型安全的替代方法,以替代传统的基于int的“位标志”,使我们能够编写更易读和易于维护的简洁代码。
EnumSet
是抽象类,其有两个实现:RegularEnumSet
、JumboEnumSet
,选择哪一个取决于实例化时枚举中常量的数量。
在很多场景中的枚举常量集合操作(如:取子集、增加、删除、containsAll
和removeAll
批操作)使用EnumSet
非常合适;如果需要迭代所有可能的常量则使用Enum.values()
。
publicclass Pizza {
privatestatic EnumSet undeliveredPizzaStatuses =
EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
private PizzaStatus status;
publicenum PizzaStatus {
…
}
public boolean isDeliverable() {
returnthis.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " +
this.getStatus().getTimeToDelivery() + " days");
}
public static List getAllUndeliveredPizzas(List input) {
return input.stream().filter(
(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
.collect(Collectors.toList());
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy()
.deliver(this);
this.setStatus(PizzaStatus.DELIVERED);
}
}
// Methods that set and get the status variable.
}
下面的测试演示了展示了 EnumSet
在某些场景下的强大功能:
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {