OnJava8-Examples/patterns/StateDemo.java

78 lines
1.5 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/StateDemo.java
// Simple demonstration of the State pattern.
2015-05-18 23:05:20 -07:00
import static net.mindview.util.Print.*;
2015-05-05 11:20:13 -07:00
interface StateBase {
void f();
void g();
void h();
void changeImp(StateBase newImp);
}
class State implements StateBase {
private StateBase implementation;
2015-05-18 23:05:20 -07:00
public State(StateBase imp) {
implementation = imp;
2015-05-05 11:20:13 -07:00
}
@Override
public void changeImp(StateBase newImp) {
implementation = newImp;
}
// Pass method calls to the implementation:
@Override
public void f() { implementation.f(); }
@Override
public void g() { implementation.g(); }
@Override
public void h() { implementation.h(); }
}
class Implementation1 implements StateBase {
@Override
2015-05-18 23:05:20 -07:00
public void f() {
print("Implementation1.f()");
2015-05-05 11:20:13 -07:00
}
@Override
2015-05-18 23:05:20 -07:00
public void g() {
print("Implementation1.g()");
2015-05-05 11:20:13 -07:00
}
@Override
2015-05-18 23:05:20 -07:00
public void h() {
print("Implementation1.h()");
2015-05-05 11:20:13 -07:00
}
@Override
public void changeImp(StateBase newImp) {}
}
class Implementation2 implements StateBase {
@Override
2015-05-18 23:05:20 -07:00
public void f() {
print("Implementation2.f()");
2015-05-05 11:20:13 -07:00
}
@Override
2015-05-18 23:05:20 -07:00
public void g() {
print("Implementation2.g()");
2015-05-05 11:20:13 -07:00
}
@Override
2015-05-18 23:05:20 -07:00
public void h() {
print("Implementation2.h()");
2015-05-05 11:20:13 -07:00
}
@Override
public void changeImp(StateBase newImp) {}
}
public class StateDemo {
static void test(StateBase b) {
b.f();
b.g();
b.h();
}
public static void main(String args[]) {
2015-05-18 23:05:20 -07:00
StateBase b =
2015-05-05 11:20:13 -07:00
new State(new Implementation1());
test(b);
b.changeImp(new Implementation2());
test(b);
}
} ///:~