码迷,mamicode.com
首页 > 其他好文 > 详细

单例 设计模式

时间:2017-12-16 15:53:11      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:one   sed   nbsp   static   sync   alt   pac   分享   pack   

一、单例模式

1,懒汉式

技术分享图片
 1 package org1;
 2 
 3 public class Singleton {
 4     private static Singleton instance = null;
 5 
 6     private Singleton() {}
 7 
 8     public static Singleton getInstance() {
 9         if (instance == null)
10             instance = new Singleton();
11         
12         return instance;
13     }
14 }
View Code

2,饿汉式

技术分享图片
 1 package org2;
 2 
 3 public class Singleton {
 4     private static Singleton instance = new Singleton();
 5 
 6     private Singleton() {}
 7 
 8     public static Singleton getInstance() {
 9         return instance;
10     }
11 }
View Code

3,双重锁式

技术分享图片
 1 package org3;
 2 
 3 //这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。
 4 public class Singleton {
 5     private static Singleton instance = null;
 6 
 7     private Singleton() {}
 8 
 9     public static Singleton getInstance() {
10         if (instance == null) {
11             synchronized (Singleton.class) {
12                 if (null == instance) {
13                     instance = new Singleton();
14                 }
15             }
16         }
17         return instance;
18     }
19 }
View Code

 

单例 设计模式

标签:one   sed   nbsp   static   sync   alt   pac   分享   pack   

原文地址:http://www.cnblogs.com/listened/p/8046533.html

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