没有状态模式
public static void main(String[] args) {
Context c = new Context();
for (int i = 0; i < 10; i++)
c.someMethod();
}
static class Context {
public static final int STATE_A = 0;
public static final int STATE_B = 1;
private int state = STATE_A;
public void someMethod() {
switch (state) {
case STATE_A:
System.out.println("StateA.SomeMethod");
state = STATE_B;
break;
case STATE_B:
System.out.println("StateB.SomeMethod");
state = STATE_A;
break;
default:
break;
}
}
}
状态模式
public static void main(String[] args) {
Context context = new Context();
context.setState(new State1());
for (int i = 0; i < 10; i++)
context.someMethod();
}
static class Context {
State state;
void setState(State state) {
this.state = state;
}
void someMethod() {
state.someMethod();
if (state instanceof State1) {
state = new State2();
} else {
state = new State1();
}
}
}
static interface State {
void someMethod();
}
static class State1 implements State {
@Override
public void someMethod() {
System.out.println("StateA.SomeMethod");
}
}
static class State2 implements State {
@Override
public void someMethod() {
System.out.println("StateB.SomeMethod");
}
}
在第一种情况下,我们只有一个对象,但在另一种情况下,我们每次调用someMethod()
方法时都会创建新对象。
- 这是对模式的正确理解吗?
- 我怎样才能解决这个问题而不创建这么多对象?
- 关于这种模式,我还需要了解什么?