首页 > 代码库 > 常用设计模式之单例
常用设计模式之单例
-
Code
1 // 饿汉式 2 public class Singleton{ 3 private Singleton(){} 4 private static final Singleton instance = new Singleton(); 5 public static Singleton getInstance(){ 6 return instance ; 7 } 8 } 9 // 静态代码块 10 public class Singleton { 11 private Singleton instance = null; 12 static { 13 instance = new Singleton(); 14 } 15 private Singleton (){} 16 public static Singleton getInstance() { 17 return this.instance; 18 } 19 } 20 21 // 懒汉式 在getInstance方法上加同步 22 public class Singleton { 23 private Singleton() {} 24 private static Singleton single=null; 25 public static synchronized Singleton getInstance() { 26 if (single == null) { 27 single = new Singleton(); 28 } 29 return single; 30 } 31 } 32 // 懒汉式 双重检查锁定 33 public class Singleton { 34 private Singleton() {} 35 private static Singleton single=null; 36 public static Singleton getInstance() { 37 if (singleton == null) { 38 synchronized (Singleton.class) { 39 if (singleton == null) { 40 singleton = new Singleton(); 41 } 42 } 43 } 44 return singleton; 45 } 46 } 47 // 静态内部类 48 public class Singleton { 49 private static class LazyHolder { 50 private static final Singleton INSTANCE = new Singleton(); 51 } 52 private Singleton (){} 53 public static final Singleton getInstance() { 54 return LazyHolder.INSTANCE; 55 } 56 }
参考:
http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html
常用设计模式之单例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。