OnJava8-Examples/patterns/StateDemo.java

88 lines
1.8 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/StateDemo.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Simple demonstration of the State pattern
2015-06-15 17:47:35 -07:00
interface StateBase {
void f();
void g();
void h();
void changeImp(StateBase newImp);
}
class State implements StateBase {
private StateBase implementation;
public State(StateBase imp) {
implementation = imp;
}
@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
public void f() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation1.f()");
2015-06-15 17:47:35 -07:00
}
@Override
public void g() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation1.g()");
2015-06-15 17:47:35 -07:00
}
@Override
public void h() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation1.h()");
2015-06-15 17:47:35 -07:00
}
@Override
public void changeImp(StateBase newImp) {}
}
class Implementation2 implements StateBase {
@Override
public void f() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation2.f()");
2015-06-15 17:47:35 -07:00
}
@Override
public void g() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation2.g()");
2015-06-15 17:47:35 -07:00
}
@Override
public void h() {
2015-11-03 12:00:44 -08:00
System.out.println("Implementation2.h()");
2015-06-15 17:47:35 -07:00
}
@Override
public void changeImp(StateBase newImp) {}
}
public class StateDemo {
static void test(StateBase b) {
b.f();
b.g();
b.h();
}
2016-01-25 18:05:55 -08:00
public static void main(String[] args) {
2015-06-15 17:47:35 -07:00
StateBase b =
new State(new Implementation1());
test(b);
b.changeImp(new Implementation2());
test(b);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Implementation1.f()
Implementation1.g()
Implementation1.h()
Implementation2.f()
Implementation2.g()
Implementation2.h()
2015-09-07 11:44:36 -06:00
*/