简体   繁体   中英

use enum as generic parameter

I have an enum day

public enum DAY { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

I want to create a generic interface so that for each day I want to have a different implementation

public interface DayLogic<T>
{
  void doLogic();
}

I want <T> to be a value of DAY enum for example

public class WednesdayLogic implements DayLogic<DAY.WEDNESDAY>
{
   @Override
   public void doLogic()
   {}    
}

is it possible or is there any alternate flow to do so?

Since there are already answers to your original question, here's what you can do that should fit your use case: since an enum is just a (restricted) class , it can implement an interface , which looks like what you need:

public enum DAY implements DayLogic { 
 SUNDAY {
  public void doLogic() {
   // sunday logic implementation
  }
 }, 
 MONDAY{
  public void doLogic() {
   // monday logic implementation
  }
 }, 
 // ...
}

You can then use it like

DAY day = decideDay();
day.doLogic();

If you don't like the individual values having the method (I don't), you can do something like

public enum DAY implements DayLogic {
 SUNDAY(new SundayLogic()),
 MONDAY(new MondayLogic()),
 // ...
 ;

 private DayLogic logicDelegate; // or Runnable, it's the same signature

 private DAY(DayLogic logic) {
  logicDelegate = logic;
 }

 public doLogic() {
  logicDelegate.run();
 }
}

Looks like you can achieve this concept by:

public enum DAY
{
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Day Logic interface and Factory initializer

public interface DayLogic
{
    void doLogic();

    public static class Factory
    {
        public DayLogic getDayLogic(DAY day)
        {
            if (DAY.WEDNESDAY.equals(day))
            {
                return new WednesdayLogic();
            }
            // ...
            return null;
        }
    }
}

WednesdayLogic Class:

public class WednesdayLogic implements DayLogic
{
    final DAY day = DAY.WEDNESDAY;

    @Override
    public void doLogic()
    {
        // TODO Auto-generated method stub

    }
}

Problem is that Enum Day is a value, not a class.

The answer from daniu is one option: the enum can implement an interface, and you do all in the interface. Especially using a constructor with DayLogic is nice.

Often that DayLogic is a later, uncoupled phenomenon. In that case use an EnumMap from the enum to your logic.

public class Dayly {
    private final Map<Day, DayLogic> logicMap = new EnumMap<>(Day.class);

    public void putLogic(Day day, DayLogic logic) {
        logicMap.put(day, logic);
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM