Is it okay to have a strategy implemented as a non-static inner class or is it considered a bad practice?

public class SomeClass{

  private final Strategy strategy;

  public void someMethod(){
   this.strategy = new Strategy();
   //call some strategy method to run an algorithm

  private class Strategy(){
    private doWork(){};

P.S: Strategy does need access to the state of the SomeClass. So can't make it static.Another option is to have Strategy as an interface and then inject a concrete Strategy inside the SomeClass constructor but at the moment I do not see this particular Strategy interface being used by another class. So thought of the first approach. However,if I do take the first approach how would I have my class work seamlessly with multiple strategies?

  • Does the strategy need access to SomeClass? I think all inner classes should be static unless they need access to the parent class. – Roger Lindsjö Mar 28 '13 at 19:21
  • @RogerLindsjö See the edit. – Subhra Mar 28 '13 at 19:26
  • 6
    It's not the strategy being used as another class that would be of benefit, but being able to switch out implementations of strategy without changing the class using it. – BlackICE Mar 28 '13 at 19:38
  • @BlackICE +1 for the comment. So you are suggesting an interface based implementation here right ? – Subhra Mar 28 '13 at 19:40
  • 1
    @HannoBinder not sure I follow, how does that imply it has to be static – BlackICE Mar 28 '13 at 20:29

I think your inner class strategy should be static because it must not work directly with the state of your class. This is how I think it should be done.

public class ExampleClass
    private final ExampleStrategy strategy;
    private int state;

    public ExampleClass(final int initialState, final ExampleStrategy strategy)
        this.state = initialState;
        this.strategy = strategy;

    public void useStrategy()
        this.state = this.strategy.modifyState(this.state);

    public static interface ExampleStrategy
        int modifyState(final int state);

    public static class IncrementStrategy implements ExampleStrategy

        public int modifyState(final int state)
            return state + 1;


    public static void main(final String[] args)
        ExampleClass eClass = new ExampleClass(10, new IncrementStrategy());



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.