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

factoryduke.FactoryRuntime Maven / Gradle / Ivy

package factoryduke;


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

import factoryduke.utils.Assert;

public class FactoryRuntime {

	private static final FactoryRuntime instance = new FactoryRuntime();

	private final Map map = new HashMap<>();

	private FactoryContext config;

	private FactoryRuntime(){
		config = new FactoryContextLoader().load();
	}

	public static FactoryRuntime getRuntime() {
		return instance;
	}

	 void register(Class clazz, String identifier, Object builder) {
		Assert.that().isTrue(builder instanceof Supplier || builder instanceof Consumer, "Please provide a Consumer or Supplier instance");

		if (map.containsKey(identifier)) {
			throw new IllegalStateException(String.format("Cannot define duplicate template with the same identifier %s for the class %s", identifier, clazz.getCanonicalName()));
		}

		map.put(identifier, builder);
	}

	 T build(Class clazz, String identifier, Consumer override) {
		final Object builder = map.computeIfAbsent(identifier, o -> {
			throw new IllegalStateException("No builder register with identifier : " + identifier + " with bloc initialization");
		});

		try {
			T instance = null;

			if (builder instanceof Consumer) {
				instance = clazz.newInstance();
				((Consumer) builder).accept(instance);
			} else {
				instance = ((Supplier) builder).get();
			}

			override.accept(instance);
			return instance;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void load() {
		new FactoriesLoader(config.getPackages()).load();
	}

	public void reset() {
		map.clear();
	}
}




© 2015 - 2026 Weber Informatics LLC | Privacy Policy