nicklasos
12/31/2015 - 12:02 PM

Java

Java

package com.nicklasos;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {

        Container c = new Container();

        c.set("A", A::new);
        c.set("B", () -> new B((A) c.get("A")));


        B b = (B) c.get("B");
        b.echo();

        B b2 = (B) c.get("B");
        b2.echo();
    }
}

class A {
    private int random;

    A() {
        random = new Random().nextInt(1000000);
    }

    public void echo() {
        System.out.println("A::echo " + random);
    }
}

class B {
    private final A a;

    B(A a) {
        this.a = a;
    }

    public void echo() {
        this.a.echo();
    }
}

class Container {
    class Box {
        private Supplier<Object> callback;
        private Object cache;

        Box(Supplier<Object> callback) {
            this.callback = callback;
        }

        public void setCache(Object cache) {
            this.cache = cache;
        }

        public Object getCache() {
            return cache;
        }

        public Supplier<Object> getCallback() {
            return callback;
        }
    }

    Map<String, Box> services = new HashMap<>();

    public void set(String name, Supplier<Object> callback) {
        services.put(name, new Box(callback));
    }

    public Object get(String name) {
        Box box = services.get(name);

        Object cache = box.getCache();
        if (cache != null) {
            return cache;
        }

        Supplier<Object> callback = box.getCallback();
        Object result = callback.get();
        box.setCache(result);

        return result;
    }
}