Design Patterns Java - Dependency Injection Php

1) Ok what have we done ?

Now we just can pass all fields values by constructors


public class ClassA
{
    private ClassB classB;

    private String one;

    private String two;

    public ClassA(ClassB classB, String one, String two)
    {
        this.classB = classB;
        this.one = one;
        this.two = two;
    }
}

public class ClassB
{
    private String one;

    private String two;

    public ClassB(String one, String two)
    {
        this.one = one;
        this.two = two;
    }
}




And let's how we create objects in application:


public class Client
{
    public void doSomething()
    {
        ClassA classA = new ClassA(new ClassB("B1", "B2"), "A1", "A2");
    }
}

public class Client2
{
    public void doSomething()
    {
        ClassA classA = new ClassA(new ClassB("B1", "B2"), "Different A1", "Different A2");
    }
}




2) Is this solution is good ?

Yes it's really quite good, definitely better than hardcoding in step1.
Yes here we have already injecting dependencies.

But still let's imagine that we have more level dependency than two like here.
Creating objects on client side would be problematic, for example we want to reuse some object like in this example we could reuse "B" instead of creating it two times.

For more levels our hierarchy tree of dependency could be big and creating this on client side could be a nightmare.

3) How we can improve this, let's create special object which responsibility would be creating dependency and in easy way client could access for all defined objects.