Alternatives to static methods on interfaces for enforcing consistency

前端 未结 7 2367
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 03:12

    Just an idea to consider: You can separate the transformation logic from the objects themselves, and then you have a fixed set of transformers, implementing the following interface :

    public interface Transformer{ 
    
      public T fromText(String text); 
    
      public String toText(T obj); 
    }
    

    Your actual data classes can have a method getTransformer() that returns the right transformer for them.

提交回复
热议问题