java设计模式之单例模式----个人笔记

单例模式单例模式是一种常见的设计模式, 

单例模式分两种:懒汉式单例、饿汉式单例。 单例模式有一下特点: 

1、单例类只能有一个实例。 

2、单例类必须自己自己创建自己的唯一实例。 3、单例类必须给所有其他对象提供这一实例。 

一、饿汉式单例在类被加载的时候,唯一实例已经被创建。这个设计模式在Java中容易实现,在别的语言中难以实现。 单例模式-懒汉式单例 

代码:

public class EagerSingleton { 

private static final EagerSingleton m_instance = new EagerSingleton(); 

private EagerSingleton() { } 

public static EagerSingleton getInstance() 

return m_instance; 

}

当类被加载的时候,static 类型的m_instance就会被事例化,保证的单利模式的自动创建条件,他是常量,保证了值不变,即保证了对象的唯一;事例的创建调用了私有的构造方法,构造方法私有保证了外界不能直接调用。 

懒汉式单例类:

 代码:  

public class LazySingleton 

 {  

private static LazySingleton m_instance = null; 

 private LazySingleton()  {  }  

synchronized public static LazySingleton getInstance() 

 {  

if(m_instance == null)  

{  

m_instance = new LazySingleton();  

}  

return m_instance;  } 

}  

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值