четверг, 23 июля 2015 г.

Singleton pattern in java

Currently I'm interested in software patterns. I'm reading the classic book: "Design patterns. Elements of reusable object-oriented software".

One of the patterns described is singleton. This is a popular pattern in java. So, how could you develop it java?

class Singleton{
private static Singleton singleton;
private Singleton{}
public static synchronized Singleton getInstance() {
if (instance == null) instance = new Singleton();
 return instance; 
 }
}

But, how about this?

public enum Singleton{
INSTANCE;
public void yourBusinessMethod(){}
}

A single-element enum type is the best way to implement a singleton. This is stated in "Effective Java".

What are the pros of this solution?
  1. no serialization problems
  2. guarantee against multiple instantiation
  3. easy to read (less) code
If you are afraid of using enum one can implement the interface for the enum. This means you can use the enum and object in method which expects the interface.

Комментариев нет:

Отправить комментарий