Skip to content

Instantly share code, notes, and snippets.

@johnmay
Created November 15, 2012 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmay/4077684 to your computer and use it in GitHub Desktop.
Save johnmay/4077684 to your computer and use it in GitHub Desktop.
CustomChemObjectBuilder
class CustomChemObjectBuilder implements IChemObjectBuilder {
private final DynamicFactory factory = new DynamicFactory(200);
public CustomChemObjectBuilder() {
// basic registration
factory.register(Element.class); // discovers Element is an instance of IElement, alternatively...
factory.register(IElement.class, Element.class); // registers Element with IElement explicitly
// only register IElement as creatable via Element("symbol") constructor
factory.register(IElement.class,
Element.class.getConstructor(String.class));
// advanced registration
// the key tells us the interface and the required parameters for construction
// the second part actually does the creation, for the examples above the 'Creator'
// is automatically built using reflection but we can gain a minor speed improvement
// and can customise construction using an anonymous class
factory.register(key(IElement.class, String.class),
new BasicCreator<Atom>(Atom.class) {
public Atom create(Object[] objects) {
return new Atom((String) objects[0]);
}
});
// above is a bit of pain, what if I don't actually want to do the creation but I do
// want to modify the element right after it's created.
// this example sets a UUID for all construction methods
factory.register(IElement.class, Element.class,
new DynamicFactory.CreationModifier<Element>() {
public void modify(Element element) {
element.setID(UUID.randomUUID().toString());
}
});
}
/**
* @inheritDoc
*/
@Override
public <T extends ICDKObject> T newInstance(Class<T> clazz, Object... params) {
// simply delegates the call
return factory.ofClass(clazz, params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment