Created
November 15, 2012 09:40
-
-
Save johnmay/4077684 to your computer and use it in GitHub Desktop.
CustomChemObjectBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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