OnJava8-Examples/patterns/StateDemo.java

69 lines
1.6 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/StateDemo.java
// (c)2021 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
// Basic demonstration of the State pattern.
2015-06-15 17:47:35 -07:00
class State {
private State implementation;
protected State() {}
public State(State imp) {
2015-06-15 17:47:35 -07:00
implementation = imp;
}
public void change(State newImp) {
2015-06-15 17:47:35 -07:00
implementation = newImp;
}
// Forward method calls to the implementation:
2015-06-15 17:47:35 -07:00
public void f() { implementation.f(); }
public void g() { implementation.g(); }
public void h() { implementation.h(); }
}
class Implementation1 extends State {
@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
}
}
class Implementation2 extends State {
@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
}
}
public class StateDemo {
static void test(State s) {
s.f();
s.g();
s.h();
2015-06-15 17:47:35 -07:00
}
2016-01-25 18:05:55 -08:00
public static void main(String[] args) {
State s = new State(new Implementation1());
test(s);
System.out.println("Changing implementation");
s.change(new Implementation2());
test(s);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Implementation1.f()
Implementation1.g()
Implementation1.h()
Changing implementation
2015-06-15 17:47:35 -07:00
Implementation2.f()
Implementation2.g()
Implementation2.h()
2015-09-07 11:44:36 -06:00
*/