单例模式是一种<<对象>><<创建型>>模式,使用单例模式,可以保证为某一个类只生成唯一的实例对象。同时提供能对该实例加以访问的全局访问方法。
单例模式实现:
1 饿汉式: 2 /* 线程安全 但效率比较低 一开始就要加载类new一个 对象 3 这是饿汉方式的单例模式*/ 4 5 6 public class Singleton { 7 //单例模式最主要的特点,就是构造函数私有化! 8 private Singleton(){} 9 //饿了嘛,上来就创建,也不管用不用!10 private static final Singleton instance=new Singleton();11 //全局访问方法!12 public static Singleton getInstance(){13 return instance;14 }15 }16 17 (2)18 //虽然是安全的 但是效率非常低在一个时候只有一个线程能访问 同时返回一个对象19 public class Singleton {20 private Singleton(){}21 private static Singleton instance = null;22 public static synchronized Singleton getInstance() {23 if (null == instance)24 instance = new Singleton();25 return instance;26 } 27 }28 29 30 双重检查:31 (4)32 /* 线程安全 并且效率高 能有多个线程访问*/33 public class Singleton {34 private Singleton() {}35 private static Singleton instance = null; 36 public static Singleton getIstance() {37 //null == instance判断两次,所以叫双重检查38 if (null == instance) {39 synchronized (Singleton.class) {40 //null == instance判断两次,所以叫双重检查41 if (null == instance) { 42 instance = new Singleton();43 }44 }45 }46 return instance;47 }48 }
原标题:设计模式之单例设计模式
关键词:设计模式