diff --git a/src/learn/simple_state/Context.java b/src/learn/simple_state/Context.java new file mode 100644 index 0000000..a3350a3 --- /dev/null +++ b/src/learn/simple_state/Context.java @@ -0,0 +1,34 @@ +package learn.simple_state; + +public class Context { + private State onState; + private State offState; + + private State currentState; + + public Context() { + onState = new OnState(this); + offState = new OffState(this); + currentState = offState; + } + + public void setCurrentState(State currentState) { + this.currentState = currentState; + } + + public State getOffState() { + return offState; + } + + public State getOnState() { + return onState; + } + + public void on() { + currentState.on(); + } + + public void off() { + currentState.off(); + } +} diff --git a/src/learn/simple_state/Main.java b/src/learn/simple_state/Main.java new file mode 100644 index 0000000..384cdc3 --- /dev/null +++ b/src/learn/simple_state/Main.java @@ -0,0 +1,12 @@ +package learn.simple_state; + +public class Main { + public static void main(String[] args) { + Context context = new Context(); + context.off(); + context.off(); + context.on(); + context.on(); + context.off(); + } +} diff --git a/src/learn/simple_state/OffState.java b/src/learn/simple_state/OffState.java new file mode 100644 index 0000000..2b2ae84 --- /dev/null +++ b/src/learn/simple_state/OffState.java @@ -0,0 +1,20 @@ +package learn.simple_state; + +public class OffState implements State { + private Context context; + + public OffState(Context context) { + this.context = context; + } + + @Override + public void on() { + context.setCurrentState(context.getOnState()); + System.out.println("Transition to on"); + } + + @Override + public void off() { + System.out.println("Already off"); + } +} diff --git a/src/learn/simple_state/OnState.java b/src/learn/simple_state/OnState.java new file mode 100644 index 0000000..4c6a786 --- /dev/null +++ b/src/learn/simple_state/OnState.java @@ -0,0 +1,20 @@ +package learn.simple_state; + +public class OnState implements State { + private Context context; + + public OnState(Context context) { + this.context = context; + } + + @Override + public void on() { + System.out.println("Already on"); + } + + @Override + public void off() { + context.setCurrentState(context.getOffState()); + System.out.println("Transition to off"); + } +} diff --git a/src/learn/simple_state/State.java b/src/learn/simple_state/State.java new file mode 100644 index 0000000..8ebef7d --- /dev/null +++ b/src/learn/simple_state/State.java @@ -0,0 +1,6 @@ +package learn.simple_state; + +public interface State { + void on(); + void off(); +}