Enums and Template Methods

|▌冷眼眸甩不掉的悲伤 提交于 2020-04-11 07:31:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!