单例设计模式
饿汉式
:一个类只能创建一个对象
- 私有化构造器
- 在类的内部创建一个类的实例,且为static
- 私有化对象,通过公共方法调用
- 此公共方法只能通过类来调用,因为设置的是static,同时类的实例也是static
饿汉先创建好:
package bank;
public class TestSingleton {
public static void main (String[] args){
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); //true
}
}
class Singleton{
//1.私有化构造器
private Singleton(){
}
//2.在类中创建一个类的实例,私有化,静态的
private static Singleton instance = new Singleton();
// 3.通过公共方法调用,此公共方法只能类调用,因为设置了 static
public static Singleton getInstance(){
return instance;
}
}
懒汉式
-
私有化构造器
-
创建一个私有的实例static 先不实例化 为 null
-
通过公共方法调用 static 在方法里面进行判断,if = null
实例化 !=null 直接returnclass Singleton{ //1.私有化构造器 private Singleton(){} //2.创建一个私有的实例为static 且值设置为null private static Singleton instance = null; //3.通过公共方法调用,static public static Singleton getInstance(){ if (instance == null){ instance = new Singleton(); } return instance; } }
懒汉式:用的时候创建
懒汉式:可能出现线程安全问题,
线程安全的懒汉式
public class SingleDemo {
private static SingleDemo s = null;
private SingleDemo(){}
public static SingleDemo getInstance(){
/*如果第一个线程获取到了单例的实例对象,
* 后面的线程再获取实例的时候不需要进入同步代码块中了*/
if(s == null){
//同步代码块用的锁是单例的字节码文件对象,且只能用这个锁
synchronized(SingleDemo.class){
if(s == null){
s = new SingleDemo();
}
}
}
return s;
}
}