In Java, I'd like to be able to define marker interfaces, that forced implementations to provide static methods. For example, for simple text-serialization/deserialization I'd like to be able to define an interface that looked something like this:
public interface TextTransformable<T>{
public static T fromText(String text);
public String toText();
Since interfaces in Java can't contain static methods though (as noted in a number of other posts/threads: here, here, and here this code doesn't work.
What I'm looking for however is some reasonable paradigm to express the same intent, namely symmetric methods, one of which is static, and enforced by the compiler. Right now the best we can come up with is some kind of static factory object or generic factory, neither of which is really satisfactory.
Note: in our case our primary use-case is we have many, many "value-object" types - enums, or other objects that have a limited number of values, typically carry no state beyond their value, and which we parse/de-parse thousands of time a second, so actually do care about reusing instances (like Float, Integer, etc.) and its impact on memory consumption/g.c.
Any thoughts?
EDIT1: To clear up some confusion - we have many, different objects fitting this pattern -really we're trying to come up with something elegant for callers with 2 semantics:
- Interfaces as contracts - unity of access (e.g. TextTransformable as a capability)
- Requiring implementation by subclasses/implementations (e.g. force them to implement their own transformation
In terms of our thoughts for Flyweight, Factories - they're both options we've considered, really we're trying to see if we can find something more elegant though than relying on JavaDoc saying "implement a Factory and delegate calls to it, or expose it at XXX location by convention"