Design Patterns Java - Dependency Injection Php

1) Ok what have we done this time ?

We just create container object when we define all objects, we called them services:


import java.util.HashMap;
import java.util.Map;

public class Container
{
    private Map<String, Object> services = new HashMap<>();

    public void buildServices()
    {
        ClassB classB = new ClassB("B1", "B2");
        services.put("serviceB", classB);

        ClassA classA1 = new ClassA(classB, "B1", "B2");
        services.put("serviceA1", classA1);

        ClassA classA2 = new ClassA(classB, "different B1", "different B2");
        services.put("serviceA2", classA2);
    }

    public Object getService(String serviceName)
    {
        return services.get(serviceName);
    }
}




We defined all objects and their dependencies in method "buildServices" and introduce to clients easy interface to get proper objects.
Dependency hierarchy in real world often can be defined in some nice format: xml, yaml or by annotation.


public class Client
{
    public void doSomething(Container container)
    {
        ClassA classA = (ClassA) container.getService("serviceA1");

        //some code
    }
}

public class Client2
{
    public void doSomething(Container container)
    {
        ClassA classA = (ClassA) container.getService("serviceA2");

        // some code
    }
}





2) What are advantages of this solution?
- we have in one place defined clear structure of dependency
- we can easily create full customizable objects
- clients are really simple, aren't they ?

It's very powerful design pattern.