Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

migrated from Mar 29 '13 at 10:59

This question came from our site for professional and enthusiast programmers.

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
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
@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());


share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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