One of the ways that comes to mind is to leave the implementation of abstract methods to separate implementation classes, for example:
interface ToyBehaviour { void execute(); } public enum Toy { DOLL(new DollBehaviour()), SOLDIER(new SoldierBehaviour()); private final ToyBehaviour behaviour; Toy(ToyBehaviour impl) { behaviour = impl; } public void execute() { behaviour.execute(); } } class DollBehaviour implements ToyBehaviour { public void execute() { System.out.println("I'm a doll."); } }
This setting allows you to create classes of behavior in separate files in case your implementation is complex enough to guarantee separation.
In the event that the implementation is simple enough to include it in one enum
class, you can put the interface and behavior classes as children of the enum class:
public enum Toy { // enum values DOLL(new DollBehaviour()), SOLDIER(new SoldierBehaviour()); private final ToyBehaviour behaviour; Toy(ToyBehaviour impl) { behaviour = impl; } public void execute() { behaviour.execute(); } // behaviour interface interface ToyBehaviour { void execute(); } // behaviour implementation (sub)classes static class DollBehaviour implements ToyBehaviour { public void execute() { System.out.println("I'm a doll."); } } // etc ... }
I would choose the first implementation myself if the hierarchy of the implementation classes is very trivial.
source share