Wednesday, July 22, 2015

Java Enum Miscs



Java Practice: When NOT to use enum's
Advantages
type safety
self documenting
valueOf method makes it easy to convert from strings to enum values
enums can have internal methods

easy to use in collections
allows you to store additional attributes with each enumeration.

Java's enum's are very much like classes. In fact, they are special classes that are inherited from the java.lang.Enum class.
enum's can't extend other enum's since they all extend java.lang.Enum

they are effectively singleton objects instantiated when they are first used.

enums are not classes/objects. Enums are good to represent static/singleton objects but should never be used as value objects or have attributes that get set during usage. 

The utility class
public enum MyUtils {;
   public static String process(String text) { /* ... */ }
}
The singleton
public enum Singleton implements SingletonService {
    INSTANCE;
    public String instanceMethod(String text) { /* ... */ }
}
An enum can implement an interface, allowing it to be mocked out where ever the interface has been used.

http://www.cnblogs.com/happyPawpaw/archive/2013/04/09/3009553.html
用法二:switch
JDK1.6之前的switch语句只支持int,char,enum类型,使用枚举,能让我们的代码可读性更强。

http://keaplogik.blogspot.com/2013/12/the-java-enum-singleton-pattern.html
  1. Serialization for free.
  2. Guaranteed one instance (Cannot instantiate more then one enum even through reflection.)
  3. Thread safe
public enum AnimalHelperSingleton {

    INSTANCE;

    private AnimalHelperSingleton(){

    }

    public Animal[] buildAnimalList(){
        final Animal[] animals = new Animal[10];

        animals[0] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Dog", true, Color.GRAY);
        animals[1] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Cat", true, Color.YELLOW);
        animals[2] = new SimpleAnimal(Animal.AnimalClass.AMPHIBIAN,
                "Frog", true, Color.GREEN);
        animals[3] = new SimpleAnimal(Animal.AnimalClass.BIRD,
                "Crow", true, Color.BLACK);
        animals[4] = new SimpleAnimal(Animal.AnimalClass.BIRD,
                "Cardinal", true, Color.RED);
        animals[5] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD,
                "Mantis", false, Color.GREEN);
        animals[6] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD,
                "Spider", false, Color.ORANGE);
        animals[7] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Tiger", true, Color.ORANGE);
        animals[8] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Bear", true, Color.BLACK);
        animals[9] = new SimpleAnimal(Animal.AnimalClass.BIRD, 
                "Owl", true, Color.BLACK);

        return animals;
    }

}
And in use:
//Call singleton to build the animal list.
Animal[] animals = AnimalHelperSingleton.INSTANCE.buildAnimalList();

http://bylijinnan.iteye.com/blog/2228411
1.enum单例简单、容易,只需几行代码:
2.enum单例自动处理序列化问题 
传统的单例实现方式(例如懒汉式饿汉式),如果它implements Serializable,那它就不再是单例了,因为readObject方法总是会返回新的对象。 
enum虽然implements Serializable,但它仍然是单例,这是由jvm保证的。 
3.enum单例是线程安全的

但是,用enum实现单例的话,它的构造函数不能抛出异常,否则会抛出Error(而不是Exception)。 
试想这样一种情况,在远程调用中,服务端抛出了Error,而客户端try-catch的是Exception,那就捕获不到出错信息,客户端就直接崩溃了。 

对三种单例实现的方式(枚举、懒汉模式、饿汉模式)进行测试,发现只有懒汉模式是抛出Exception,其它两种都是抛出ExceptionInInitializerError。 
这很好解释,因为懒汉模式是在方法(getInstance)调用中出错,而枚举方式和饿汉方式都是在类加载(Class initialization)时出错(The constructors are invoked when the enum class is initialized)。 
类实例化出错显然更严重一些。 

所以,在枚举方式和饿汉方式实现单例时,注意不要让构造函数抛出异常。 

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts