Singleton模式的两种实现方法

  在设计模式中,有一种叫Singleton模式的,用它可以实现一次只运行一个实例。就是说在程序运行期间,某个类只能有一个实例在运行。这种模式用途比较广泛,会经常用到,下面是Singleton模式的两种实现方法:

  1、饿汉式

None.gif public   class  EagerSingleton
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
private static readonly EagerSingleton instance = new EagerSingleton();
ExpandedSubBlockStart.gifContractedSubBlock.gif            
private EagerSingleton()dot.gif{}
InBlock.gif            
public static EagerSingleton GetInstance()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return instance;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

  2、懒汉式

None.gif          public   class  LazySingleton
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
private static LazySingleton instance = null;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
private LazySingleton()dot.gif{}
InBlock.gif            
public static LazySingleton GetInstance()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (instance == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    instance 
= new LazySingleton();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
return instance;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

  两种方式的比较:饿汉式在类加载时就被实例化,懒汉式类被加载时不会被实例化,而是在第一次引用时才实例化。这两种方法没有太大的差别,用哪种都可以。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值