简体   繁体   中英

Design pattern to switch a state for a set of functions

I have a series of instance functions in a class. There is also a boolean instance variable that designates an object state. Almost all the instance functions depend on this boolean state. Their body looks like

int f() {

   if (state) {
      //do stuff
   }
   else {
      // do other stuff
   }
}

In addition to that some function are swapped by the state. So if state is true then when user calls f() it actually is run. But when state is false then when user calls f() what happens is that antiF() is run.

So some functions have switches inside them and some functions get swapped completely.

If I was doing this with C++ I would probably use function pointers. How would I do this with Java? A Strategy pattern?

Looks like you want the state pattern . Instead of having each function check for the state, you pull these functions into a state interface and have separate implementations for each state:

public interface State {
  void f();
  void g();
  void h();
}

public class StateA : State {
  public void f() { do something; }
  ...
}

public class StateB : State {
  public void f() { do something else; }
  ...
}

Then instead of a boolean variable, you would maintain a specific State instance:

State currentState = new StateA();
...
currentState = new StateB();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM