Java多例设计模式
class TrafficLight{ private String lightType; private static final TrafficLight GREENLIGHT = new TrafficLight("GreenLight"); private static final TrafficLight REDLIGHT = new TrafficLight("RedLight"); private static final TrafficLight YELLOWLIGHT = new TrafficLight("YellowLight"); private TrafficLight(String lightType){ this.lightType = lightType; } public static TrafficLight getInstance(String ch){ switch(ch){ case "GreenLight": return GREENLIGHT; case "RedLight": return REDLIGHT; case "YellowLight": return YELLOWLIGHT; default: return null; } } public String toString(){ return this.lightType; } } public class TrafficLightDemo { public static void main(String[] args) { TrafficLight GreenLight = TrafficLight.getInstance("GreenLight"); TrafficLight RedLight = TrafficLight.getInstance("RedLight"); TrafficLight YellowLight = TrafficLight.getInstance("YellowLight"); System.out.println(GreenLight); System.out.println(RedLight); System.out.println(YellowLight); } }