单例模式(Singleton Pattern)是一个比较简单的模式,其定义如下:
确保某一个类 只有一个实例,而且自行实例化并向整个系统提供这个实例。
饿汉式创建单例:(饿汉式创建单例不存在线程安全以及指令重排等问题)
public class Singleton {
private static final Singleton singleton = new Singleton();
//限制产生多个对象
private Singleton(){
};
//返回创建的单例对象(获取对象的方法一定要是static,不然永远获取不到。。。)
public static Singleton getInstance(){
return singleton;
}
public void doSomething(){
System.out.println("创建了一个单例对象,hashcode:" + this.hashCode());
}
}
public class Main {
public static void main(String[] args) {
//两个相同对象的hashcode不一致
Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
//单例对象的hashcode一致
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
instance1.doSomething();
instance2.doSomething();
}
}
输出:
o1的hashcode:1554874502
o2的hashcode:1846274136
创建了一个单例对象,hashcode:1639705018
创建了一个单例对象,hashcode:1639705018
懒汉式创建单例模式(一定要加锁,并且双重校验,不然是线程不安全的)
public class Singleton2 {
//volatile关键字防止指令重排
private volatile static Singleton2 singleton2;
//限制产生多个对象
private Singleton2(){
}
public static Singleton2 getInstance(){
if (null == singleton2){
synchronized (Singleton2.class){
//双重校验达到线程安全
if (null == singleton2){
singleton2 = new Singleton2();
}
}
}
return singleton2;
}
public void doSomething(){
System.out.println("创建了一个单例对象,hashcode:" + this.hashCode());
}
}
public class Main {
public static void main(String[] args) {
//两个相同对象的hashcode不一致
Object o1 = new Object();
Object o2 = new Object();
System.out.println("o1的hashcode:" + o1.hashCode());
System.out.println("o2的hashcode:" + o2.hashCode());
//单例对象的hashcode一致
Singleton2 instance1 = Singleton2.getInstance();
Singleton2 instance2 = Singleton2.getInstance();
instance1.doSomething();
instance2.doSomething();
}
}
输出:
o1的hashcode:1554874502
o2的hashcode:1846274136
创建了一个单例对象,hashcode:1639705018
创建了一个单例对象,hashcode:1639705018