public class Sing {
private Sing(){};
private final static Sing instance=new Sing();
public static Sing getInstance() {
return instance;
}
}
饿汉模式(静态代码块)
public class Sing {
private Sing(){};
private static Sing instance;
static {
instance=new Sing();
}
public static Sing getInstance() {
return instance;
}
}
懒汉式(线程不安全) -->在实际开发过程中千万不要使用!!!
public class Sing {
private Sing(){};
private static Sing instance;
public static Sing getInstance(){
if(instance==null){
instance=new Sing();
}
return instance;
}
}
懒汉式(线程安全,同步方法) ->在实际开发过程中不推荐使用!!!
public class Sing {
private Sing(){};
private static Sing instance;
public static synchronized Sing getInstance(){
if(instance==null){
instance=new Sing();
}
return instance;
}
}
懒汉式(线程安全,同步代码块) -->不推荐使用!!!!
public class Sing {
private Sing(){};
private static Sing instance;
public static Sing getInstance(){
if(instance==null){
synchronized (Sing.class) {
instance = new Sing();
}
}
return instance;
}}
双重检查 -->推荐使用!!!!
public class Sing {
private Sing(){};
private static Sing instance;
public static synchronized Sing getInstance(){
if(instance==null) {
synchronized (Sing.class) {
if (instance==null) {
instance=new Sing();
}
}
}
return instance;
}
}
枚举
public enum Sing {
instance;
public void show(){
System.out.println("111");
}
}
public class TestSing {
public static void main(String[] args) {
Sing sing01=Sing.instance;
Sing sing02=Sing.instance;
System.out.println(sing01==sing02);
System.out.println(sing01.hashCode());
System.out.println(sing02.hashCode());
}
}
静态内部类 -->推荐使用!!!!
public class Sing {
private static Sing instance;
private Sing(){};
private static class UserSing{
private static final Sing userSing=new Sing();
}
public static synchronized Sing getInstance(){
return UserSing.userSing;
}
}
public class TestSing {
public static void main(String[] args) {
Sing sing01 = Sing.getInstance();
Sing sing02 = Sing.getInstance();
System.out.println(sing01 == sing02);
System.out.println(sing01.hashCode());
System.out.println(sing02.hashCode());
}
}