Alternatives to static methods on interfaces for enforcing consistency

前端 未结 7 2366
孤城傲影
孤城傲影 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
    2020-12-05 03:20

    If you are running in Java 5 or higher, you can use the enum type - all of those are, by definition, singletons. So you could something like:

    public enum MyEnumType {
        Type1,
        Type2,
        //....
        TypeN;
    
        //you can do whatever you want down here
        //including implementing interfaces that the enum conforms to.
    
    }
    

    This way the memory problem goes away, and you can have single instances of behavior implemented.


    Edit: If you don't have access to enums (1.4 or earlier) or, for some other reason, they don't work for you, I would recommend a Flyweight pattern implementation.

提交回复
热议问题