锁定老帖子 主题:状态模式(State)
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2010-06-18
感觉还是抛哥写得比较犀利
抛出异常的爱 写道 enum Light{ 红灯(1000),黄灯(5000),绿灯(5000); //顺序调整. int sleepping; private Light(int x) { this.sleepping = x ; } public Light change(){ System.out.println(name()); sleep(); return next(); } public Light next(){ return values()[((ordinal()+1)%(values().length))]; } public static void main(String[] args) { Light light = Light.红灯; while(true){ light = light.change(); } } private void sleep() { try { Thread.sleep(this.sleepping); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
|
返回顶楼 | |
发表时间:2010-06-18
对抛哥代码修改了一下
/** * 定义枚举类 * @author * */ public enum EnumLight { 红灯(500), 黄灯(100), 绿灯(500),蓝灯(300); int sleepping; int min;//循环次数下线 int max;//循环次数上线 private EnumLight(int x) { this.sleepping = x; } } /** * 定义灯的抽象类 * @author * */ public abstract class Light { public abstract void sleep(); public abstract void change(); /** * 判断是否要限制循环 * @param min * @param max * @param isLimited * @return */ public boolean isLooped(int min,int max, boolean isLimited){ return (isLimited == true) ? (min < max) && isLimited : true; } } /** * 采用枚举实现状态模式 * * @author * */ public class TrafficLight extends Light { private EnumLight el; public TrafficLight(EnumLight el) { this.el = el; } /** * 改变状态 */ public void change() { System.out.println(el); sleep(); this.el = el.values()[(el.ordinal() + 1) % el.values().length]; this.el.min++; } @Override public void sleep() { try { Thread.sleep(el.sleepping); } catch (InterruptedException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { EnumLight el = EnumLight.红灯; el.min = 0;// 循环次数下线 el.max = 4;// 循环次数上线 TrafficLight tl = new TrafficLight(el); boolean isLimited = false;// 是否需要限制上线下线 boolean isLooped = tl.isLooped(el.min, el.max, isLimited); while (isLooped) { isLooped = tl.isLooped(el.min, el.max, isLimited); tl.change(); } } } |
|
返回顶楼 | |