【发布时间】:2018-06-05 23:18:21
【问题描述】:
我有两个环境PROD 和STAGING。在生产环境中,我们有三个数据中心ABC、DEF 和PQR,并且暂存有一个数据中心CORP。每个数据中心都有几台机器,我为它们定义了常量,如下所示:
// NOTE: I can have more machines in each dc in future
public static final ImmutableList<String> ABC_SERVERS = ImmutableList.of("tcp://machineA:8081", "tcp://machineA:8082");
public static final ImmutableList<String> DEF_SERVERS = ImmutableList.of("tcp://machineB:8081", "tcp://machineB:8082");
public static final ImmutableList<String> PQR_SERVERS = ImmutableList.of("tcp://machineC:8081", "tcp://machineC:8082");
public static final ImmutableList<String> STAGING_SERVERS = ImmutableList.of("tcp://machineJ:8087","tcp://machineJ:8088");
现在我在同一个类中定义了另一个常量,它按 DC 分组到每种环境类型的机器列表。
public static final ImmutableMap<Datacenter, ImmutableList<String>> PROD_SERVERS_BY_DC =
ImmutableMap.<Datacenter, ImmutableList<String>>builder()
.put(Datacenter.ABC, ABC_SERVERS).put(Datacenter.DEF, DEF_SERVERS)
.put(Datacenter.PQR, PQR_SERVERS).build();
public static final ImmutableMap<Datacenter, ImmutableList<String>> STAGING_SERVERS_BY_DC =
ImmutableMap.<Datacenter, ImmutableList<String>>builder()
.put(Datacenter.CORP, STAGING_SERVERS).build();
现在在其他班级,根据我在(Utils.isProd()) 的环境,我得到PROD_SERVERS_BY_DC 或STAGING_SERVERS_BY_DC。
Map<Datacenter, ImmutableList<String>> machinesByDC = Utils.isProd() ? Utils.PROD_SERVERS_BY_DC : Utils.STAGING_SERVERS_BY_DC;
现在我认为这可以用某种 Enum 以更好的方式表示,而不是像上面那样定义常量,但我无法弄清楚我该怎么做?我从这个开始,但对如何为每个 DC 拥有单个键,然后将多个值作为该 DC 的机器列表,然后我还需要按环境对它们进行分组感到困惑。
// got confuse on how can I make key (DC) and list of values (machines) for each environment type.
public enum DCToMachines {
abc(tcp://machineA:8081", "tcp://machineA:8082"),
private final List<String> machines;
private final Datacenter datacenter;
...
}
【问题讨论】:
标签: java oop design-patterns data-structures enums