2

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?

4

1 に答える 1

6

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();
于 2012-07-13T16:23:10.327 に答える