[置顶]单例设计模式 (代码实现)

 

  ---单例设计模式之饿汉式---

 

  创建SingleInstance类

 1 /**
 2  * 单例设计模式之饿汉式
 3  */
 4 public class SingleInstance {    
 5     /**
 6      * 私有化构造方法
 7      */
 8     private SingleInstance() {}
 9     /**
10      * 成员变量
11      */
12     private static SingleInstance instance = new SingleInstance() ;
13     /**
14      * 提供一个静态的成员方法,返回该对象
15      */
16     public static SingleInstance getInstance() {
17         return instance ;
18     }
19 }

 

  创建测试类SingleInstanceDemo

 

 1 /**
 2  * 单例设计模式的思想:    保证该类在内存中只有一个实例(对象)
 3  * 优点节省内存,提高内存利用率
 4  */
 5 public class SingleInstanceDemo {
 6     
 7     public static void main(String[] args) {
 8         
 9         // 调用方法获取对象
10         SingleInstance instance1 = SingleInstance.getInstance() ;
11         SingleInstance instance2 = SingleInstance.getInstance() ;
12         
13         // 输出
14         System.out.println(instance1 == instance2);
15     }
16 }

 

 

-------------------------------------------------------------------------------------------------------------

 

  ---单例设计模式之懒汉式---

 

  创建SingleInstance2

 1 /**
 2  * 单例设计模式之懒汉式
 3  * 
 4  * 面试中写那种单例设计模式呢?
 5  *         面试中写懒汉式:    因为懒汉式体现了两种思想, 第一种线程问题 , 第二种 延迟加载
 6  * 
 7  *    开发中写饿汉式
 8  */
 9 public class SingleInstance2 {
10     /**
11      * 私有化构造方法
12      */
13     private SingleInstance2() {}
14     /**
15      * 提供一个成员变量
16      */
17     private static SingleInstance2 instance = null ;
18     /**
19      * 提供一个静态的成员方法
20      */
21     public static synchronized SingleInstance2 getInstance() {
22     
23         if(instance == null){
24             instance = new SingleInstance2() ;
25         }
26         return instance ;
27     }
28 }

 

  创建测试类SingleInstanceDemo2

 

 1 public class SingleInstance2Demo {
 2     
 3     public static void main(String[] args) {
 4         
 5         // 获取对象
 6         SingleInstance2 instance1 = SingleInstance2.getInstance() ;
 7         SingleInstance2 instance2 = SingleInstance2.getInstance() ;
 8         
 9         // 比较
10         System.out.println(instance1 == instance2);
11         
12     }
13 
14 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jusenr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值