在Java编程语言中,单例模式(饿汉模式)应用的例子如下述代码所示:
public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor suppresses // default public constructor private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
在Java编程语言中,单例模式(懒汉模式)应用的例子如下述代码所示:
public class Singleton { private static Singleton INSTANCE = null; // Private constructor suppresses // default public constructor private Singleton() {} public static synchronized Singleton getInstance() { if(INSTANCE == null){ INSTANCE = new Singleton(); } return INSTANCE; } }