There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

  1. The intent allows an object to change its behavior when its internal state changes.
  2. The class diagram

  3. The instance
Interface State {/** * @param CTX record State */ void exc(Context CTX); /** * print name * @param name name */ void name (String name); } static class State1 implements State { @Override public void exc(Context ctx) { ctx.setSt(this); } @Override public void name (String name) { System.out.println("state1 --- " + name); } } static class State2 implements State { @Override public void exc(Context ctx) { ctx.setSt(this); } @Override public void name (String name) { System.out.println("state2 --- " + name); } } static class Context { private State st; public State getSt() { return st; } public void setSt(State st) { this.st = st; }}Copy the code
  1. test
public static void main(String[] args) { LinkedList<State> stL = new LinkedList<>(); stL.offer(new State1()); stL.offer(new State2()); String name = "myName"; String name = "myName"; Context ctx = new Context(); StL. ForEach (stL. ForEach (st -> {stL. ForEach (st -> {stL. ForEach (st -> {stL. ctx.getSt().name(name); }); }Copy the code

Running results:

state1 --- myName
state2 --- myName
Copy the code

Want to see more? Please visit:Design patterns