饿汉式
静态常量饿汉式的优点是:在类装载的时候就完成实例化,没有达到Lazy Loading的效果,并且避免了线程同步问题。
它的缺点是:如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class adaDemo3 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println(instance1==instance);
System.out.println(instance1.hashCode());
System.out.println(instance.hashCode());
}
}
class Singleton{
private final static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance(){
return instance;
}
}
懒汉式(双重检查)
效率可以,线程安全,推荐使用。
class Singleton{
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance(){
if (instance==null){
synchronized (Singleton.class){
if (instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
懒汉式(静态内部类)
利用JVM加载类时是线程安全的机制,推荐使用。
class Singleton{
private Singleton (){}
private static class InternalClass{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return InternalClass.instance;
}
}
枚举类
public class adaDemo3 {
public static void main(String[] args) {
Singleton instance = Singleton.INSTANCE;
Singleton instance1 = Singleton.INSTANCE;
System.out.println(instance1==instance);
System.out.println(instance1.hashCode());
System.out.println(instance.hashCode());
instance.test();
}
}
enum Singleton{
INSTANCE;
void test(){
System.out.println("test");
}
}
标签:Singleton,Java,System,模式,instance,static,private,单例,out
From: https://www.cnblogs.com/yan061/p/17929941.html