今天在看张老师的交通灯管理系统的时候,他设计Lamp这个枚举的时候,构造函数用的是String,老师说,这是为了避免使用为定义的变量。有没有其他方法?我记得学C++有这个功能- package cn.itcast.traffic;
- public enum Lamp {
- S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","N2S",false),E2S("W2N","S2N",false),
- N2S(null,null,false),N2E(null,null,false),W2E(null,null,false),W2N(null,null,false),
- S2E(null,null,true),E2N(null,null,true),N2W(null,null,true),W2S(null,null,true);
- private String opposite;
- private String next;
- private boolean lighted;
-
- private Lamp(String opposite, String next, boolean lighted) {
- this.opposite = opposite;
- this.next = next;
- this.lighted = lighted;
- }
- public boolean isLighted() {
- return lighted;
- }
-
- public void light() {
- lighted = true;
- if (opposite != null) {
- Lamp.valueOf(opposite).light();
- }
- }
-
- public Lamp shutdown() {
- lighted = false;
- Lamp lamp = null;
- if (opposite != null)
- Lamp.valueOf(opposite).shutdown();
- if (next != null) {
- lamp = Lamp.valueOf(next);
- lamp.light();
- }
- return lamp;
-
- }
- }
复制代码 |