vb.net下的单例模式
发布时间:2020-12-16 22:41:27 所属栏目:大数据 来源:网络整理
导读:单例模式确保某对象只能实例化一次,因此可以确保程序中所有对象访问同一个对象,但是也存在一个弊端,如,不能解决删除单个对象的问题等,因为缺少实际的开发运用,对性能以及单例的优缺点就不会太明白,这里重点总结一下单例模式的5种拓展实现。 原文详见
单例模式确保某对象只能实例化一次,因此可以确保程序中所有对象访问同一个对象,但是也存在一个弊端,如,不能解决删除单个对象的问题等,因为缺少实际的开发运用,对性能以及单例的优缺点就不会太明白,这里重点总结一下单例模式的5种拓展实现。 原文详见:http://www.cnblogs.com/psunny/archive/2010/06/18/1760133.html 1 、单例模式的简单实现:(这种方式创建是线程不安全的) Public NotInheritable Class UserDataReaderToEntityStrategy
Shared singleInstance As UserDataReaderToEntityStrategy = Nothing
'私有化构造函数
Private Sub New()
End Sub
'创建静态方法,用于取得全局唯一实例
Public Shared ReadOnly Property GetInstance() As UserDataReaderToEntityStrategy
Get
If singleInstance Is Nothing Then
singleInstance = New UserDataReaderToEntityStrategy
End If
Return singleInstance
End Get
End Property
End Class
2、安全线程的实现 Public NotInheritable Class UserDataReaderToEntityStrategy
Shared singleInstance As UserDataReaderToEntityStrategy = Nothing
Shared ReadOnly padlock As New Object()
'私有化构造函数
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance() As UserDataReaderToEntityStrategy
Get
'这里添加一个锁,保证了线程的安全
SyncLock padlock
If singleInstance Is Nothing Then
singleInstance = New UserDataReaderToEntityStrategy
End If
End SyncLock
Return singleInstance
End Get
End Property
End Class
Public NotInheritable Class UserDataReaderToEntityStrategy
Shared singleInstance As UserDataReaderToEntityStrategy = Nothing
Shared ReadOnly padlock As New Object()
'私有化构造函数
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance() As UserDataReaderToEntityStrategy
Get
'这里添加一个锁,保证了线程的安全
If singleInstance Is Nothing Then
SyncLock padlock
If singleInstance Is Nothing Then
singleInstance = New UserDataReaderToEntityStrategy
End If
End SyncLock
End If
Return singleInstance
End Get
End Property
End Class
4、静态初始化(首选方式) Public NotInheritable Class UserDataReaderToEntityStrategy
Shared singleInstance As UserDataReaderToEntityStrategy = Nothing
Shared Sub New()
End Sub
'私有化构造函数
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance() As UserDataReaderToEntityStrategy
Get
Return singleInstance
End Get
End Property
End Class
Public NotInheritable Class UserDataReaderToEntityStrategy
Shared singleInstance As UserDataReaderToEntityStrategy = Nothing
'私有化构造函数
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance() As UserDataReaderToEntityStrategy
Get
Return Nested.singleInstance
End Get
End Property
Private Class Nested
Shared Sub New()
End Sub
Friend Shared ReadOnly singleInstance As New UserDataReaderToEntityStrategy()
End Class
End Class
作者:
Sunny Peng
出处:
http://www.cnblogs.com/psunny/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |