Alternatives to static methods on interfaces for enforcing consistency

前端 未结 7 2346
孤城傲影
孤城傲影 2020-12-05 02:43

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

相关标签:
7条回答
  • 2020-12-05 03:30

    It seems like you need to separate the factory out from the created object.

    public interface TextTransformer<T> {
        public T fromText(String text);
        public String toText(T source);
    }
    

    You can register TextTransformer classes however you like:

    public class FooTextTransformer implements TextTransformer<Foo> {
        public Foo fromText(String text) { return ...; }
        public String toText(Foo source) { return ...; }
    }
    

    If you want FooTextTransformer to be a singleton, you can use a container like Spring to enforce that. Google has initiated a project to remove all manually enforced singletons from their codebase, but if you want to do an old-fashioned singleton, you could use a utility class:

    public class TextTransformers {
        public static final FooTextTransformer FOO = new FooTextTransformer();
        ...
        public static final BarTextTransformer BAR = new BarTextTransformer();
    }
    

    In your client code:

    Foo foo = TextTransformers.FOO.fromText(...);
    ...
    foo.setSomething(...);
    ...
    String text = TextTransformers.FOO.toText(foo);
    

    This is just one approach off the top of my head.

    0 讨论(0)
提交回复
热议问题