[备忘] Java enum 两点用法

Effective Java 2nd edition中说: 在Java5以后, 最好的单例模式应该是用 enum 来实现:

enum MySingleton {  
  INSTANCE;  
  public static MySingleton getInstance() {  
    return INSTANCE;  
  }  
}

见一篇中文的分析 http://blog.csdn.net/java2000_net/archive/2009/03/12/3983958.aspx

Java enum总是能玩出花, 再看一个用enum来实现Functor的例子

package com.smithfox.test;

public enum People{
  CHINESE { protected void sayhello(String name) {
      System.out.println("你好,"+name);
  }},

  ENGLISH { protected void sayhello(String name) {
      System.out.println("Hello,"+name);
  }},

  RUSSIAN { protected void sayhello(String name) {
      System.out.println("Здравствуйте,"+name);
  }};

  protected abstract void sayhello(String name);

  public void greeting(String name) {
    //System.out.println("握手");
    sayhello(name);
    System.out.println("挥手,bye!");
  }
  
  public static void main(String[] argvs){
    CHINESE.greeting("smithfox");
    ENGLISH.greeting("smith");
    RUSSIAN.greeting("fox");
  }
}

这个例子是不是比 经典的OOP例子, 要精简多了!  上面例子中的People已经是一个Java Functor了, 这个比用内部类来实现方便多了, 不过因为enum的静态特性(不能继承, 不能多实例化), 适用场景较少!

smithfox | Wednesday 11 May 2011 at 2:11 pm | | Java       

two comments

Chanel iPhone 6 Plus Cases

The iPad Mini 3 houses a standard headphone jack and Apple’s Lightning connector port. Hidden under the Home button is a fingerprint scanner that allows for biometric authenticated access into your tablet.

Chanel iPhone 6 Plus Cases, (URL) - 20-04-’15 18:24
YSL iPhone 6 Cases

A few of the Gionee phone’s stronger points are dual LED flash, an 18% larger display, microSD slot for storage expansion, and a sapphire camera lens. We won’t list all of the different aspects here, as you will see them all when you watch the video.

YSL iPhone 6 Cases, (URL) - 18-06-’15 16:30
(optional field)
(optional field)
为阻止垃圾广告, 请在提交评论前, 回答一个简单问题(Please answer an simple question)
Remember personal info?
Notify
Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.