How do I provide an implementation for enumeration values in Java?

I have the value of the enumeration class. Assuming that it will grow over time, I hope the user adding the new enumeration value can also provide coercion somewhere

public enum DayType {
    SUNDAY,MONDAY;
}

Mentioned in class

class X{
DateType dateType;
..
}

And used in some other courses

if (x.getDateType().equals(DayType.SUNDAY)) {
...
}else if(x.getDateType().equals(DayType.MONDAY)){
..
}

Therefore, if someone adds a datetype, he should be forced to add the necessary conditions in the if else logic above If possible, it is best to add functional interfaces?

I can't enforce it in an enumeration class because it must have a spring dependency

Solution

The real answer is: don't do that

If you have some "types" and you know that this "type" will see new avatars over time, which requires different behaviors, the answer is to use abstract classes and polymorphism

If you use an if / else chain or switch statement, it doesn't matter: do you have this idea:

if (someObject.getSomething() == whatever) { then do this } else { that }

Is a bad practice!

If so, you should use such a switch statement in the factory to return different subclass instances, and then call the "common" method on these objects

Your current approach is a) externalizing knowledge about internal states, and b) enforcing dependencies in a variety of ways

This is the beginning of the spaghetti code! It's best to step back and consider more OOP solutions!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>