Design Patterns(二):Singleton Pattern--VB代码

意图:
保证一个类仅有一个实例,并提供一个访问它的全局访问点。

适用性:
当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
当这个唯一实例是通过子例化可扩展的,并且客户应该无需要更改代码就能使用一个扩展的实例时。

实现:
1.       私有的构造函数防止在外部实例化。
2.       保存唯一实例的静态的私有变量。
3.       初始化并获得唯一实例的静态方法。

      ●简单实现:
      
优点:可以使用附加功能(例如,对子类进行实例化)
                  惰性实例化,避免应用程序启动时实例化不必要的Singleton实例。
      缺点:多线程的环境下将得到Singleton的多个实例

ExpandedBlockStart.gif ContractedBlock.gif Public   NotInheritable   Class SingletonClass Class SingletonClass
InBlock.gif    
Private Shared me_instance As Singleton = Nothing
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub New()Sub New()
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public ReadOnly Shared Property Instance()Property Instance()
InBlock.gif        
Get
InBlock.gif            
If me_instance Is Nothing Then
InBlock.gif                me_instance 
= New Singleton()
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
Return me_instance
InBlock.gif        
End Get
ExpandedSubBlockEnd.gif    
End Property

ExpandedBlockEnd.gif
End Class

   ●安全的线程:
   
优点:可多线程访问。
   缺点:增加了额外的开销,损失了性能。

ExpandedBlockStart.gif ContractedBlock.gif Public   NotInheritable   Class SingletonClass Class SingletonClass
InBlock.gif    
InBlock.gif    
Private Shared me_instance As Singleton = Nothing
InBlock.gif    
Private Shared syncObject As Object = New Object
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub New()Sub New()Sub New()Sub New()
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public ReadOnly Shared Property Instance()Property Instance()
InBlock.gif        
Get
InBlock.gif            
SyncLock syncObject
InBlock.gif                
If me_instance Is Nothing Then
InBlock.gif                    me_instance 
= New Singleton()
InBlock.gif                
End If
InBlock.gif
InBlock.gif                
Return me_instance
InBlock.gif            
End SyncLock
InBlock.gif        
End Get
ExpandedSubBlockEnd.gif    
End Property

ExpandedBlockEnd.gif
End Class

   ●双重锁定:
   
优点:解决了线程并发的问题避免在每个Instance属性方法的调用中都出现独占锁定。可以为构造函数添加参数。
   缺点:无法实现延迟初始化。 

ExpandedBlockStart.gif ContractedBlock.gif Public   Class SingletonClass Class SingletonClass
InBlock.gif
InBlock.gif        
Private Shared _instance As Singleton
InBlock.gif        
Private Shared syncObject As Object = New Object    'Lock synchronization object
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif        
Protected Sub New()Sub New()
ExpandedSubBlockEnd.gif        
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Shared ReadOnly Property Instance()Property Instance()
InBlock.gif            
Get
InBlock.gif                
If _instance Is Nothing Then
InBlock.gif                    
SyncLock syncObject
InBlock.gif                        
If _instance Is Nothing Then
InBlock.gif                            _instance 
= New Singleton
InBlock.gif                        
End If
InBlock.gif                    
End SyncLock
InBlock.gif                
End If
InBlock.gif
InBlock.gif                
Return _instance
InBlock.gif            
End Get
ExpandedSubBlockEnd.gif        
End Property

ExpandedBlockEnd.gif    
End Class

    ●静态初始化:
   
优点:第一次引用类的成员时创建实例。标记为sealed(NotInheritable)阻止变量标记为ReadOnly,只能在静态初始化期间或在类构造函数中分配变量
   缺点:对实例化控制权较少
   注释:实现Singleton的首选方法

ExpandedBlockStart.gif ContractedBlock.gif Public   Class SingletonClass Class SingletonClass
InBlock.gif        
Public Shared ReadOnly Instance As New Singleton
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Protected Sub New()Sub New()Sub New()Sub New()
ExpandedSubBlockEnd.gif        
End Sub

InBlock.gif
ExpandedBlockEnd.gif
End Class

  ●延迟初始化:
   
优点:初始化工作由静态成员(Nested类)来完成

ExpandedBlockStart.gif ContractedBlock.gif Public   NotInheritable   Class SingletonClass Class SingletonClass
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Protected Sub New()Sub New()
ExpandedSubBlockEnd.gif        
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Shared ReadOnly Property Instance()Property Instance()
InBlock.gif            
Get
InBlock.gif                
Return Nested.instance
InBlock.gif            
End Get
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Private Class NestedClass Nested
ExpandedSubBlockStart.gifContractedSubBlock.gif            
Shared Sub New()Sub New()Sub New()Sub New()
ExpandedSubBlockEnd.gif            
End Sub

InBlock.gif
InBlock.gif            
Friend Shared ReadOnly instance As New Singleton
ExpandedSubBlockEnd.gif        
End Class

ExpandedBlockEnd.gif
End Class

实例:

ContractedBlock.gif ExpandedBlockStart.gif 最优化的例子
None.gif' Singleton pattern -- Real World example
None.gif

None.gif
Imports System
None.gif
Imports System.Collections
None.gif
Imports System.Threading
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Namespace DoFactoryNamespace DoFactory.GangOfFour.Singleton.RealWorld
InBlock.gif    
' MainApp test application
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Class MainAppClass MainApp
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Private Shared Sub Main()Sub Main()
InBlock.gif            
Dim b1 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b2 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b3 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b4 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif
InBlock.gif            
'Same instance?
InBlock.gif
            If b1 = b2 AndAlso b2 = b3 AndAlso b3 = b4 Then
InBlock.gif                Console.WriteLine(
"Same instance" & Chr(10& "")
InBlock.gif            
End If
InBlock.gif            
For i As Integer = 0 To 14
InBlock.gif
InBlock.gif                
'All are the same instance -- use b1 arbitrarily
InBlock.gif
                'Load balance 15 server requests
InBlock.gif
                Console.WriteLine(b1.Server)
InBlock.gif            
Next
InBlock.gif
InBlock.gif            
'Wait for user
InBlock.gif
            Console.Read()
ExpandedSubBlockEnd.gif        
End Sub

ExpandedSubBlockEnd.gif    
End Class

InBlock.gif
InBlock.gif    
' "Singleton"
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Class LoadBalancerClass LoadBalancer
InBlock.gif        
Private Shared instance As LoadBalancer
InBlock.gif        
Private servers As New ArrayList()
InBlock.gif
InBlock.gif        
Private random As New Random()
InBlock.gif
InBlock.gif        
'Lock synchronization object
InBlock.gif
        Private Shared [syncLockAs New Object()
InBlock.gif
InBlock.gif        
'Constructor (protected)
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Protected Sub New()Sub New()
InBlock.gif            
' List of available servers
InBlock.gif
            servers.Add("ServerI")
InBlock.gif            servers.Add(
"ServerII")
InBlock.gif            servers.Add(
"ServerIII")
InBlock.gif            servers.Add(
"ServerIV")
InBlock.gif            servers.Add(
"ServerV")
ExpandedSubBlockEnd.gif        
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Shared Function GetLoadBalancer()Function GetLoadBalancer() As LoadBalancer
InBlock.gif            
'Support multithreaded applications through
InBlock.gif
            ' 'Double checked locking' pattern which (once
InBlock.gif
            ' the instance exists) avoids locking each
InBlock.gif
            ' time the method is invoked
InBlock.gif
            If instance Is Nothing Then
InBlock.gif                
SyncLock [syncLock]
InBlock.gif                    
If instance Is Nothing Then
InBlock.gif                        instance 
= New LoadBalancer()
InBlock.gif                    
End If
InBlock.gif                
End SyncLock
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
Return instance
ExpandedSubBlockEnd.gif        
End Function

InBlock.gif
InBlock.gif        
'Simple, but effective random load balancer
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Public ReadOnly Property Server()Property Server() As String
InBlock.gif            
Get
InBlock.gif                
Dim r As Integer = random.[Next](servers.Count)
InBlock.gif                
Return servers(r).ToString()
InBlock.gif            
End Get
ExpandedSubBlockEnd.gif        
End Property

ExpandedSubBlockEnd.gif    
End Class

ExpandedBlockEnd.gif
End Namespace

 

ContractedBlock.gif ExpandedBlockStart.gif 最优美的例子
None.gif' Singleton pattern -- Real World example
None.gif

None.gif
Imports System
None.gif
Imports System.Collections
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Namespace DoFactoryNamespace DoFactory.GangOfFour.Singleton.NETOptimized
InBlock.gif
InBlock.gif    
'MainApp test application
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Class MainAppClass MainApp
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Private Shared Sub Main()Sub Main()
InBlock.gif            
Dim b1 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b2 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b3 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif            
Dim b4 As LoadBalancer = LoadBalancer.GetLoadBalancer()
InBlock.gif
InBlock.gif            
'Confirm these are the same instance
InBlock.gif
            If b1 is b2 AndAlso b2 is b3 AndAlso b3 is b4 Then
InBlock.gif                Console.WriteLine(
"Same instance" & Chr(10& "")
InBlock.gif            
End If
InBlock.gif            
For i As Integer = 0 To 14
InBlock.gif
InBlock.gif                
'All are the same instance -- use b1 arbitrarily
InBlock.gif
                'Load balance 15 requests for a server
InBlock.gif
                Console.WriteLine(b1.Server)
InBlock.gif            
Next
InBlock.gif
InBlock.gif            
'Wait for user
InBlock.gif
            Console.Read()
ExpandedSubBlockEnd.gif        
End Sub

ExpandedSubBlockEnd.gif    
End Class

InBlock.gif
InBlock.gif    
' Singleton
ExpandedSubBlockStart.gifContractedSubBlock.gif
    NotInheritable Class LoadBalancerClass LoadBalancer
InBlock.gif        
'Static members are lazily initialized.
InBlock.gif
        ' .NET guarantees thread safety for static initialization
InBlock.gif
        Private Shared ReadOnly instance As New LoadBalancer()
InBlock.gif
InBlock.gif        
Private servers As New ArrayList()
InBlock.gif        
Private random As New Random()
InBlock.gif
InBlock.gif        
'Note: constructor is private.
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Private Sub New()Sub New()
InBlock.gif            
'List of available servers
InBlock.gif
            servers.Add("ServerI")
InBlock.gif            servers.Add(
"ServerII")
InBlock.gif            servers.Add(
"ServerIII")
InBlock.gif            servers.Add(
"ServerIV")
InBlock.gif            servers.Add(
"ServerV")
ExpandedSubBlockEnd.gif        
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Shared Function GetLoadBalancer()Function GetLoadBalancer() As LoadBalancer
InBlock.gif            
Return instance
ExpandedSubBlockEnd.gif        
End Function

InBlock.gif
InBlock.gif        
'Simple, but effective load balancer
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Public ReadOnly Property Server()Property Server() As String
InBlock.gif            
Get
InBlock.gif                
Dim r As Integer = random.[Next](servers.Count)
InBlock.gif                
Return servers(r).ToString()
InBlock.gif            
End Get
ExpandedSubBlockEnd.gif        
End Property

ExpandedSubBlockEnd.gif    
End Class

ExpandedBlockEnd.gif
End Namespace


我对单件模式的理解:
1.封装全局变量
2.保证线程安全

参考资料:
《C#面向对象设计模式纵横谈系列课程(2)》  李建中老师
《.Net设计模式(2):单件模式(Singleton Pattern)》 Terrylee老师

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值