单例设计模式:即某个类在整个系统中只能有一个实例,对象可被获取和使用的代码模式。
1)某个类只有一个实例。
构造器必须是私有化
2)它必须自行创建这个实例。
含有一个该类的静态变量来保存这个唯一的实例
3)它必须自行向整个系统提供这个实例(两种其中都可以)
- 直接暴露这个静态变量
- 用静态变量的get方法获取
恶汉式
public class Singleton01 { public static final Singleton01 INSTANCE=new Singleton01(); private Singleton01() { } }
静态代码块
public class Singleton02 { private static Singleton02 instance=null; private String name; static { Properties properties=new Properties(); try { properties.load(Singleton02.class.getClassLoader().getResourceAsStream("db.properties")); } catch (IOException e) { e.printStackTrace(); } String sname = properties.getProperty("name"); instance=new Singleton02(sname); } private Singleton02(String name){ this.name=name; } public static Singleton02 getInstance(){ return instance; } }
枚举
public enum Singleton03 { INSTANCE; }
懒汉式
public class Singleton04 { private static Singleton04 instance=null; private Singleton04(){ } public static Singleton04 getInstance(){ if(instance==null){ instance=new Singleton04(); } return instance; } }
加锁
public class Singleton05 { private static Singleton05 instance=null; private Singleton05(){ } public synchronized static Singleton05 getInstance(){ if(instance==null){ instance=new Singleton05(); } return instance; } }
双重检查
public class Singleton06 { private static Singleton06 instance=null; private Singleton06(){ } public static Singleton06 getInstance(){ if(instance==null){ synchronized (Singleton06.class){ if(instance==null){ instance=new Singleton06(); } } } return instance; } }
内部静态类方式
public class Singleton07 { private Singleton07(){ } private static class Instance{ static Singleton07 instance=new Singleton07(); } public static Singleton07 getInstance(){ return Instance.instance; } }
posted on
浙公网安备 33010602011771号