反射与单例设计模式
单例设计模式的核心本质在于:类内部的构造方法私有化,在类的内部产生实例化对象之后通过static方法获取实例化对象进行类中的结构调用,单例设计模式一共有两类:懒汉式、饿汉式,饿汉式的单例是不再本次讨论范围之内的,主要来讨论懒汉式单例设计模式。
范例:观察懒汉式单例设计模式的问题
package cn.mldn.demo;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
for (int x = 0; x < 3; x++) {
new Thread(()->{
Singleton.getInstance().print();
},"单例消费端-" + x).start();
}
}
}
class Singleton {
private static Singleton instance = null;
private Singleton() {
System.out.println("【" + Thread.currentThread().getName() + "】********* 实例化Singleton类对象 **********");
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton() ;
}
return instance ;
}
public void print() {
System.out.println("www.mldn.cn");
}
}
程序运行结果:
【单例消费端-2】********* 实例化Singleton类对象 **********
【单例消费端-0】********* 实例化Singleton类对象 **********
www.mldn.cn
【单例消费端-1】********* 实例化Singleton类对象 **********
www.mldn.cn
www.mldn.cn
单例设计模式的最大特点是在整体的运行过程之中只允许产生一个实例化对象,这个时候会发现当有了若干线程之后,当前的程序就可以产生多个实例化对象了,那么此时就不是单例设计模式。此时问题造成的关键在于代码本身出现了不同步的情况,而要想解决的关键核心就在于需要进行同步处理,同步自然可以想到synchronized关键字。
范例:修改getInstance()方法进行同步处理
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton() ;
}
return instance ;
}
这个时候的确是进行了同步处理,但是这个同步的代价有些大,因为效率会低。因为整体代码里面实际上只有一块部分需要进行同步处理,instance 对象的实例化处理部分,在这样的情况下会发现同步加的有些草率了。
范例:更加合理的进行同步处理
package cn.mldn.demo;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
for (int x = 0; x < 3; x++) {
new Thread(()->{
Singleton.getInstance().print();
},"单例消费端-" + x).start();
}
}
}
class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
System.out.println("【" + Thread.currentThread().getName() + "】********* 实例化Singleton类对象 **********");
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton() ;
}
}
}
return instance ;
}
public void print() {
System.out.println("www.mldn.cn");
}
}
面试题:请编写单例设计模式
【100%】直接编写一个饿汉式的单例设计模式,并且实现构造方法私有化;
【120%】在Java中那里面使用到单例设计模式了?Runtime类、Spring框架;
【200%】懒汉式单例设计模式的问题?