首页 > 其他 > 详细

单例 设计模式

时间:2017-12-16 15:20:35      阅读:186      评论:0      收藏:0      [点我收藏+]

一、单例模式

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

 

单例 设计模式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!