还记得不少年前,面试就让在白板上写个单例模式,当时技术渣渣,还写的是class A.面试官还说,你就不能写个Singleton.java
单例模式:即某个类在整个系统中只有一个实例对象可被获取和使用的代码模式面试
(1) 直接实例化饿汉式编程
/** * 饿汉式(直接建立实例对象) * 直接经过类名调用 * * @author kevin * @date 2019/7/8 11:23 */ public class Singleton1 { public static final Singleton1 INSTANCE = new Singleton1(); private Singleton1() { } }
(2)枚举式设计模式
/** * 饿汉式(枚举) * * @author kevin * @date 2019/7/8 11:29 */ public enum Singleton2 { INSTANCE; }
(3) 静态代码块安全
import java.io.IOException; import java.util.Properties; /** * @author kevin * @date 2019/7/8 13:35 */ public class Singleton3 { public static final Singleton3 INSTANCE; private String info; static { try { Properties properties = new Properties(); properties.load(Singleton3.class.getClassLoader().getResourceAsStream("sing.properties")); INSTANCE = new Singleton3(properties.getProperty("info")); } catch (IOException e) { throw new RuntimeException(e); } } private Singleton3(String info) { this.info = info; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } @Override public String toString() { return "Singleton3{" + "info='" + info + '\'' + '}'; } }
注意:这里还有个properties文件多线程
info=kevin
测试ide
Singleton3 s = Singleton3.INSTANCE; System.out.println(s);
结果函数
Singleton3{info='kevin'}
(1)线程不安全测试
public class Singleton4 { private static Singleton4 instance; public static Singleton4 getInstance(){ if(instance == null){ instance = new Singleton4(); } return instance; } private Singleton4(){ } }
(2) 线程安全this
/** * @author kevin * @date 2019/7/8 13:56 */ public class Singleton5 { private static Singleton5 instance; public static Singleton5 getInstance() { if (instance == null) { synchronized (Singleton5.class) { if (instance == null) { instance = new Singleton5(); } } } return instance; } private Singleton5() { } }
(3)静态内部类 线程安全
/** * 静态内部类不会自动随着外部类的加载而初始化 * * @author kevin * @date 2019/7/8 13:56 */ public class Singleton6 { private static class Inner { private static final Singleton6 INSTANCE = new Singleton6(); } public static Singleton6 getInstance() { return Inner.INSTANCE; } private Singleton6() { } }
注意:静态内部类不会自动随着外部类的加载而初始化
好了,玩的开心。