标签:style blog http color ar sp strong div on
背景:
用户操作鼠标,涉及的动作有左击、右击、双击。每种动作对应一种状态,状态的切换对应着不同的鼠标点击事件。
类图:
状态接口类:
/** * 状态接口 * */ public interface State { public void change(); }
鼠标移入类:
public class MouseoverState implements State{ public void change(){ System.out.println("鼠标移入了。"); } }
鼠标移出类:
public class MouseoutState implements State{ public void change() { System.out.println("鼠标移出了。"); } }
鼠标类:
// 被观察者 public class Mouse extends Observable{ public enum STATE {MOUSEOVER,MOUSEOUT}; private State state ; public State getState() { return state; } public void setState(State state) { System.out.println("鼠标状态发生了变化。"); this.state = state; setChanged() ; notifyObservers(state); } }
用户操作类:
/** * 操作类,同时也是观察者 * */ public class User implements Observer{ @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub State state = (State)arg ; state.change() ; } }
调用类:
public class Main { public static void main(String[] args) { User user = new User() ; Mouse mouse = new Mouse(); State state = new MouseoutState() ; // 添加被观察者 mouse.addObserver(user); // 状态被改变 mouse.setState(state); } }
如有不当之处,请给我留言,方便交流与讨论。
标签:style blog http color ar sp strong div on
原文地址:http://www.cnblogs.com/xinzhuangzi/p/4101242.html