cdc.mf.model.MfFactory Maven / Gradle / Ivy
The newest version!
package cdc.mf.model;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import cdc.util.lang.Introspection;
/**
* This class is used to create {@link MfModel models} and {@link MfWrapper element wrappers}.
*/
public final class MfFactory {
private final Map, Function extends MfElement, MfWrapper>> wrapperFactories;
public static final MfFactory EMPTY = builder().build();
private MfFactory(Builder builder) {
this.wrapperFactories = Collections.unmodifiableMap(new HashMap<>(builder.wrapperFactories));
}
MfWrapper newWrapper(MfElement element) {
final Function extends MfElement, MfWrapper> f = wrapperFactories.get(element.getClass());
if (f == null) {
throw new IllegalArgumentException("No wrapper factory associated to " + element.getClass().getSimpleName());
} else {
return f.apply(Introspection.uncheckedCast(element));
}
}
boolean canWrap(MfElement element) {
return wrapperFactories.containsKey(element.getClass());
}
/**
* @return A new model builder.
*/
public MfModel.Builder model() {
return new MfModel.Builder(this);
}
/**
* Creates a clone of a model.
*
* @param model The model to duplicate.
* @return A clone of {@code model}.
*/
public MfModel duplicate(MfModel model) {
return model().set(model)
.build();
}
/**
* @return An instance of {@link MfFactory.Builder}.
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final Map, Function extends MfElement, MfWrapper>> wrapperFactories = new HashMap<>();
/**
* Registers a wrapper factory for an element class.
*
* @param The element type.
* @param elementClass The element class.
* @param wrapperFactory The wrapper factory that should return an instance
* of {@link MfWrapper} attached to the passed element.
* @return This builder.
*/
public Builder add(Class elementClass,
Function wrapperFactory) {
this.wrapperFactories.put(elementClass, wrapperFactory);
return this;
}
public MfFactory build() {
return new MfFactory(this);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy