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

org.squirrelframework.foundation.component.SquirrelSingletonProvider Maven / Gradle / Ivy

Go to download

foundation module of squirrel framework which provided event driven infrastructure and a finite state machine implementation.

There is a newer version: 0.3.10
Show newest version
package org.squirrelframework.foundation.component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.google.common.base.Preconditions;

public class SquirrelSingletonProvider implements SquirrelComponent, SquirrelSingleton {

    private static SquirrelSingletonProvider instance = new SquirrelSingletonProvider();

    public static SquirrelSingletonProvider getInstance() {
        return instance;
    }

    public static void setInstance(SquirrelSingletonProvider instance) {
        SquirrelSingletonProvider.instance = instance;
    }
    
    private Map instanceRegistry = new ConcurrentHashMap();
    
    public  void register(Class componentClass, Object instance) {
        Preconditions.checkArgument(componentClass.isAssignableFrom(instance.getClass()));
        instanceRegistry.put(componentClass.getName(), instance);
    }
    
    public void unregister(Class componentClass) {
        instanceRegistry.remove(componentClass.getName());
    }
    
    public void clearRegistry() {
        instanceRegistry.clear();
    }
    
    public  T get(Class componentClass) {
        Object instance = instanceRegistry.get(componentClass.getName());
        if(instance==null) {
            try {
                instance = SquirrelProvider.getInstance().newInstance(componentClass);
            } catch(Exception e) {
                instance = null;
            }
            if(instance!=null) {
                register(componentClass, instance);
            }
        } 
        return instance!=null ? componentClass.cast(instance) : null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy