码迷,mamicode.com
首页 > 编程语言 > 详细

Java 实现单例模式

时间:2014-12-02 16:38:25      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:java   设计模式   

  1. public class Singleton {  
  2.     private static Singleton intance;  
  3.     private Singleton() {}  
  4.       
  5.     public static Singleton getInstance() {  
  6.         /* 
  7.          * 一开始多线程进来,遇到锁,一个线程进去,是为空,new对象; 后续线程进入,不为空,不操作;最后直接返回 
  8.          * 对象不为空,再有多个线程进入该函数,不为空,不执行加锁操作,直接返回 
  9.          */  
  10.         if (intance == null) {  
  11.             synchronized (Singleton.class) {  
  12.                 if (intance == null) {  
  13.                     intance = new Singleton();  
  14.                 }  
  15.             }  
  16.         }  
  17.         return intance;  
  18.     }  
  19. }  
  20.   
  21. class Singleton1 {// 懒汉式   
  22.     private static Singleton1 intance = new Singleton1();//懒的,程序运行的时候就加载出来了  
  23.     private Singleton1() {}  
  24.       
  25.     public static Singleton1 getInstance() {  
  26.         return intance;  
  27.     }  
  28. }  
  29.   
  30. class Singleton2 {// 饿汉式  
  31.     private static Singleton2 intance;  
  32.     private Singleton2() {}  
  33.       
  34.     public static Singleton2 getInstance() {//用到的时候 才加载  
  35.         if (intance == null) {  
  36.             intance = new Singleton2();  
  37.         }  
  38.         return intance;  
  39.     }  
  40. }  
  41.   
  42. class Singleton3 {// 饿汉式 线程安全  
  43.     private static Singleton3 intance;  
  44.     private Singleton3() {}  
  45.       
  46.     public synchronized static Singleton3 getInstance() {//用到的时候 才加载, 加锁  多线程调用,都有一个加锁的动作  
  47.         if (intance == null) {  
  48.             intance = new Singleton3();  
  49.         }  
  50.         return intance;  
  51.     }  
  52. }  
  53.   
  54. class Singleton4 {// 饿汉式 线程安全  
  55.     private static Singleton4 intance;  
  56.     private Singleton4() {}  
  57.       
  58.     public static Singleton4 getInstance() {//用到的时候 才加载  
  59.         synchronized (Singleton4.class) {// 加锁 效率跟3差不多  
  60.             if (intance == null) {  
  61.                 intance = new Singleton4();  
  62.             }  
  63.         }  
  64.         return intance;  
  65.     }  
  66. }

Java 实现单例模式

标签:java   设计模式   

原文地址:http://blog.csdn.net/shineflowers/article/details/41679891

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!