问题
Enum is basically a special class type, and can have methods and fields just like any other class. Any one know about the Enums Template Methods. Please give a real example for Template Methods on Enums. And can you explain about Enum Reverse Lookups.
回答1:
Java 5.0 Enum tricks, specially have a look on the video.
Here is a simple example of a "command" enumeration:
public enum Toy {
DOLL() {
@Override public void execute() {
System.out.println("I'm a doll.");
}
},
SOLDIER() {
@Override public void execute() {
System.out.println("I'm a soldier.");
}
};
//template method
public abstract void execute();
}
Here objects Doll and Soldier both have a different implementation of the function execute()
.
回答2:
Applying the "Template Method" design pattern, one can create enumerations that are factories or command objects, but a defined set of objects. Here is a simple example of a "command" enumeration:
you will also get explanation of Enum Reverse Lookups over the above link
来源:https://stackoverflow.com/questions/8799936/enums-and-template-methods