- package com.itheima.demo1;
- public class Lamp {
- /*
- * S2N,S2W,E2W,E2S是本类的核心,控制好他们就控制好了信号灯
- */
- public final Lamp S2N = new Lamp("N2S", "S2W", false);
- public final Lamp S2W = new Lamp("N2E", "E2W", false);
- public final Lamp E2W = new Lamp("W2E", "E2S", false);
- public final Lamp E2S = new Lamp("W2N", "S2N", false);
- // S2N,S2W,E2W,E2S对应的oppo对象
- public final Lamp N2S = new Lamp(false);
- public final Lamp N2E = new Lamp(false);
- public final Lamp W2E = new Lamp(false);
- public final Lamp W2N = new Lamp(false);
- // 右转信号灯
- public final Lamp S2E = new Lamp(true);
- public final Lamp E2N = new Lamp(true);
- public final Lamp N2W = new Lamp(true);
- public final Lamp W2S = new Lamp(true);
- private String next;
- private String oppo;
- private boolean isGreen;
- // 私有化构造器
- private Lamp(String oppo, String next, boolean isGreen) {
- this.oppo = oppo;
- this.next = next;
- this.isGreen = isGreen;
- }
- // 私有化构造器
- private Lamp(boolean isGreen) {
- this.isGreen = isGreen;
- }
- /*
- * 通过信号灯名获得得对应信号灯
- */
- public Lamp getLamp(String lamp) {
- switch (lamp) {
- case "S2N":
- return S2N;
- case "S2W":
- return S2W;
- case "E2W":
- return E2W;
- case "E2S":
- return E2S;
- default:
- return null;// 不会被执行
- }
- }
- public boolean isGreen() {
- return isGreen;
- }
- public void toGreen() {
- this.isGreen = true;
- getLamp(oppo).isGreen = true;
- System.out.println(this.toString() + "is green.");
- }
- public Lamp toRed() {
- this.isGreen = false;
- getLamp(oppo).isGreen = false;
- getLamp(next).isGreen = true;
- getLamp(getLamp(next).oppo).isGreen = true;
- return getLamp(next);
- }
- @Override
- public String toString() {
- if (this == S2N) {
- return "S2N";
- } else if (this == S2W) {
- return "S2W";
- } else if (this == E2W) {
- return "E2W";
- } else if (this == E2S) {
- return "E2S";
- }
- return null; // 不会被执行
- }
- }
复制代码
还没试,应该差不离了 |