0

I'm trying to understand how to combine them (if possible) in this Java 1.7 code:

class View{
private State _state;
}

abstract class State{
protected View _view;
}

class UserState extends State{}
class AdminState extends State {}

I've tried to understand them better using these articles: dependency-injection and state-design-pattern. But I ended only more confused.

My questions are:

  • Can I somehow inject States in the View class and avoid keeping State instance ?

  • What I am missing in my code to achieve it?

Thanks in advance.

ekostadinov
  • 6,880
  • 3
  • 29
  • 47
  • 1
    [This question is suffering from the XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) please edit it to fix it. In other words, while I know those two patterns I don't know enough about what you're trying to do to be able to help you. – durron597 Oct 08 '14 at 13:31
  • +1 for the correction. Question is updated. – ekostadinov Oct 08 '14 at 13:50

1 Answers1

1

The problem you're having is a common one for dependency injection beginners. You are trying to do Circular Dependency Injection. I consider this article to be the canonical reference on the subject. Read that article, it does a better job than I am about to do.

However, briefly: You are trying to do this (picture stolen from article):

+---------+      +---------+
|    A    |<-----|    B    |
|         |      |         |
|         |----->|         |
+---------+      +---------+

Which class do you inject first? If you are trying to create B, you need an A. But you can't make A without B. And on and on.

You could do a workaround like this:

public class A {
    private final B b;
    A(B b) {
        this.b = b;
    }
}

public class B {
    private /*not-final*/ A a;
    public void setA(A a) {
        this.a = a;
    }
}

But this is a code smell. It's better to instead do:

                         +---------+
+---------+              |    B    |
|    A    |<-------------|         |
|         |              |         |
|         |    +---+     |         |
|         |--->| C |<----|         |
|         |    +---+     +---------+
+---------+

Read the article for the code sample

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158