Blog

It's a Wonderful Life

java单例模式

2017-05-07 22:03 Posted in Learn with Java , DesignPattern

static域方式:

class Singleton
{
    private static final Singleton instance = new Singleton();
     
    private Singleton()
    {
        throw new AssertionError();
    }

    public static Singleton getInstance()
    {
        return instance;
    }
    
    public void show()
    {
        System.out.println("Singleton instance showing...");
    }
}

enum语法:

public enum SINGLETON
{
    INSTANCE;

    public void show()
    {
        System.out.println("Singleton instance showing...");
    }
}

推荐使用enum语法来实现单例,因为这样做

  1. 写法简单
  2. static域方式相比,使用enumlazy loaded的,即只有在方法被调用的时候对象才被创建
  3. enum原生提供Serialization支持
  4. enum是默认线程安全的