All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.leanovate.pragmatic.ioc.SingletonScope Maven / Gradle / Ivy

The newest version!
package de.leanovate.pragmatic.ioc;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

public class SingletonScope extends AbstractScope {
    private volatile Map instances = new HashMap<>();

    @Override
    @SuppressWarnings("unchecked")
    public  T getInstance(final Class injectedClass, final Optional name,
            final Supplier supplier) {

        final String key = name.map((n) -> injectedClass.getName() + ":" + n).orElse(injectedClass.getName());
        T instance = (T) instances.get(key);

        if (instance == null) {
            synchronized (this) {
                instance = (T) instances.get(key);

                if (instance == null) {
                    instance = createInstance(key, supplier);
                    addinstance(key, instance);
                }
            }
        }
        return instance;
    }

    @Override
    public void bind(final Object instance) {

        Objects.requireNonNull(instance);
        addinstance(instance.getClass().getName(), instance);
    }

    @Override
    public  void bind(final Class injectedClass, final T instance) {

        addinstance(Objects.requireNonNull(injectedClass).getName(), Objects.requireNonNull(instance));
    }

    private synchronized void addinstance(final String key, final Object instance) {
        final Map newInstances = new HashMap<>(instances);
        newInstances.put(key, instance);
        this.instances = newInstances;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy