How to add common methods for a few Java enums? (abstract class ancestor?)

后端 未结 5 665
孤街浪徒
孤街浪徒 2021-01-04 07:01

I have a few Java enums as such

public enum Aggregation
{
    MORTGAGE( \"Mortgage\" ),
    POOLS( \"Pools\" ),
    PORTFOLIO( \"Portfolio\" );

    private         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 07:22

    Favor composition over inheritance and programming for the sake of interfaces. Since Enums are classes (not regular, but still - classes) you can create some field containing shared logic, let the enum implement you interface and delegate implementation to this field.

    Relevant code snippets:

    Shared interface

    public interface MyInterface {
    
        void someMethod();
    
    }
    

    Logic implementation

    public class MyInterfaceImpl implements MyInterface {
    
        public void someMethod() {
            System.out.println("Do smth...");
        }
    
    }
    

    First enum

    public enum EnumA implements MyInterface {
        ;
    
        private MyInterface impl = new MyInterfaceImpl();
    
        public void someMethod() {
            impl.someMethod();
        }
    
    }
    

    Second enum

    public enum EnumB implements MyInterface {
        ;
    
        private MyInterface impl = new MyInterfaceImpl();
    
        public void someMethod() {
            impl.someMethod();
        }
    
    }
    

    Please do note that EnumA and EnumB are not really code duplication, since that is plain delegation (valid, in my opinion). Also please note that everything is nicely glued together by using interface.

提交回复
热议问题