一、单例设计模式
单例设计模式分为饿汉式跟懒汉式
懒汉式:先不生产对象,等有人来要的时候,我再看我有没有
饿汉式:直接new了一个对象,有人来就给他.
使用反射改进多线程问题不同步的问题。
class SingletonE {
private static final SingletonE INSTANCE =new SingletonE();
private SingletonE() {}
public static SingletonE getInstance() {
return INSTANCE;
}
public String getInfo() {
return "这是一个饿汉式单例对象";
}
}
class SingletonL {
private static SingletonL intance;
private SingletonL() {}
public static SingletonL getInstance() {
if(intance==null) {
intance=new SingletonL();
}
return intance;
}
public String getInfo() {
return "这是一个懒汉式单例对象";
}
}
二、完整代码
package reflect;
class SingletonReflection {
private static volatile SingletonReflection singletonReflection;
private SingletonReflection() {
System.out.println(Thread.currentThread().getName() + "实例了我");
}
public static SingletonReflection getSingleInstance() {
if (singletonReflection == null) {
synchronized (SingletonReflection.class) {
if (singletonReflection == null) {
singletonReflection = new SingletonReflection();
}
}
}
return singletonReflection;
}
public void print() {
System.out.println("我来了");
}
}
public class SingletonDome {
public static void main(String[] args) {
for (int i = 0 ; i < 3 ; i++) {
new Thread(() -> {
SingletonReflection.getSingleInstance().print();
} , "线程" + i).start();
}
}
}
三、面试题
【100%】编写一个饿汉式单例设计模式;
1、构造方法私有化
2、拥有一个私有的静态单例对象,在属性的时候就new了
3、拥有一个静态的获取单例对象的方法
【120%】Java开发中哪些地方用到了单例设计模式?
1、Runtime
【200%】懒汉式单例设计模式的问题?
1、多线程不安全问题
2、如果将同步加在静态方法上的话效率低
3、锁上new的之后要再判断
4、属性中可以加上 volatile关键字对其直接操作