状态模式STATE

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 06:02   61   0

public class StateToggle {

public static void main(String[] args) throws IOException {
InputStreamReader is = new InputStreamReader(System.in);
int ch;
Button btn = new Button();
while (true) {
System.out.print("Press <Enter>");
ch = is.read();
ch = is.read();
btn.push();
}
}
}

class OFF extends State {
private static OFF inst = new OFF();

private OFF() {
}

public static State instance() {
return inst;
}

// /// 6. Override only the necessary methods /////
public void push(Button b) {
// /// 7. The "wrappee" may callback to the "wrapper" /////
b.setCurrent(ON.instance());
System.out.println(" turning ON");
}
}


class ON extends State {
private static ON inst = new ON();

private ON() {
}

public static State instance() {
return inst;
}
}

class State {
public void push(Button b) { // 5. Default behavior
b.setCurrent(OFF.instance()); // can go in the base
System.out.println(" turning OFF"); // class
}
}


// /// 1. The "wrapper" class ///// // State ----
class Button { // ON OFF
// /// 2. The "current" state object ///// // OFF ON
private State current;

public Button() {
current = OFF.instance();
}

public void setCurrent(State s) {
current = s;
}

// /// 3. The "wrapper" always delegates to the "wrappee" /////
public void push() {
current.push(this);
}
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP