代码分享如下:
public class SimpleSingleton { private static SimpleSingleton singleInstance = new SimpleSingleton(); //Marking default constructor private //to avoid direct instantiation. private SimpleSingleton() { } //Get instance for class SimpleSingleton public static SimpleSingleton getInstance() { return singleInstance; } } /**另一种实现*/ public enum SimpleSingleton { INSTANCE; public void doSomething() { } } //Call the method from Singleton: SimpleSingleton.INSTANCE.doSomething();--Hurry
本文介绍了Java中两种单例模式的实现方法:静态内部类方式和枚举方式。详细解释了每种方法的工作原理,并通过示例代码演示了如何在实际项目中应用这些模式。
1万+

被折叠的 条评论
为什么被折叠?



