首页 > 其他 > 详细

单例设计模式

时间:2018-08-27 15:17:26      阅读:138      评论:0      收藏:0      [点我收藏+]

饿汉式:

 1 public class Singleton {
 2     // 直接创建对象
 3     public static Singleton instance = new Singleton();
 4 
 5     // 私有化构造函数
 6     private Singleton() {
 7     }
 8 
 9     // 返回对象实例
10     public static Singleton getInstance() {
11         return instance;
12     }
13 }

懒汉式:

 1 public class Singleton {
 2     // 声明变量
 3     private static volatile Singleton singleton = null;
 4 
 5     // 私有构造函数
 6     private Singleton() {
 7     }
 8 
 9     // 提供对外方法
10     public static Singleton getInstance() {
11         if (singleton == null) {
12             synchronized (Singleton.class) {
13                 if (singleton == null) {
14                     singleton = new Singleton();
15                 }
16             }
17         }
18         return singleton;
19     }
20 
21 }

 

单例设计模式

原文:https://www.cnblogs.com/ffeiyang/p/9542329.html

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