Singleton模式的两种实现方法

本文介绍了Singleton设计模式的两种实现方法:饿汉式和懒汉式。饿汉式在类加载时即完成实例化,适用于类加载时即需要初始化的情况;懒汉式则在首次使用时进行实例化,适用于延迟加载的需求。
  在设计模式中,有一种叫Singleton模式的,用它可以实现一次只运行一个实例。就是说在程序运行期间,某个类只能有一个实例在运行。这种模式用途比较广泛,会经常用到,下面是Singleton模式的两种实现方法:

  1、饿汉式

None.gifpublic 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        }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值