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

单例设计模式

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

标签:on()   let   设计   public   单例设计模式   str   变量   size   设计模式   

饿汉式:

 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 }

 

单例设计模式

标签:on()   let   设计   public   单例设计模式   str   变量   size   设计模式   

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

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