Do not limit your challenges.. Challenge your limits

BTemplates.com

Search This Blog

Powered by Blogger.

About Me

My photo
kathmandu, Bagmati, Nepal
I am Software developer based on Nepal.I have started coding since mid of 1995 with QBasic.My interest in software development covers a broad range of technologies from assembly to the Microsoft .NET platform to Java, Linux to Windows, Windows Mobile to Android, desktop to web to mobile, and many others. But from 2007 I am just working on Java mainly working on Java EE platform and decided just to go with it. I really like to learn new stuff and share things with others which is my main objective in creating this blog.

ArchUnit : Java architecture test library

Finally I have found the required library which will enforce architecture patterns . ArchUnit  . Currently I am exploring it and will upd...

Wednesday, July 10, 2013

Singleton pattern in java


Although Singletons are not encouraged because it can make it difficult to test it's clients, we can create it in three ways.
  1. With Public final filed
  2. With Static Factory
  3. With Enum

With Public final filed


public class Cache {

    public static final Cache INSTANCE = new Cache();
    private static Map<String, Object> map = new HashMap<>();

    private Cache() {
    }

    public void put(String key, Object data) {
        map.put(key, data);
    }

    public Object get(String key) {
        return map.get(key);
    }
}

With Static factory
public class Cache {
    
    private static final Cache INSTANCE = new Cache();
    private static Map<String, Object> map = new HashMap<>();

    private Cache() {
    }

    public void put(String key, Object data) {
        map.put(key, data);
    }

    public Object get(String key) {
        return map.get(key);
    }
    
    public static Cache getInstance(){
        return INSTANCE;
    } 
}

With Enum
public enum Cache {

    INSTANCE;
    private static Map<String, Object> map = new HashMap<>();

    public void put(String key, Object data) {
        map.put(key, data);
    }

    public Object get(String key) {
        return map.get(key);
    }
}

In  Effective Java ,Joshua Bloch encourage to use Enum for Singleton because it is more concise,provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation,even in the face of sophisticated serialization or reflection attacks.

0 comments:

Post a Comment