日期:2013-11-08  浏览次数:20632 次

单件模式

Singleton Pattern



Singleton 模式,它包含在创造性模式系列中。

创造性模式指示如何以及何时创建对象。Singleton 模式可以保证一个类有且只有一个实例,并提供一个访问它的全局访问点。在程序设计过程中,有很多情况需要确保一个类只能有一个实例。例如,系统中只能有一个窗口管理器、一个打印假脱机,或者一个数据引擎的访问点。PC机中可能有几个串口,但只能有一个COM1实例。

其结构如下:




我们可以定义一个Spooler类,实现Singleton 模式



Public Class Spooler

Private Shared Spool_counter As Integer

Private Shared glbSpooler As Spooler

Private legalInstance As Boolean

'-----

Private Sub New()

MyBase.New()

If Spool_counter = 0 Then '建立并且保存这个实例

glbSpooler = Me '保存实例

Spool_counter = Spool_counter + 1 '计数

legalInstance = True

Else

legalInstance = False

Throw New SpoolerException

End If

End Sub

'-----

Public Shared Function getSpooler() As Spooler

Try

glbSpooler = New Spooler()

Catch e As Exception

Throw e '实例已经存在

Finally

getSpooler = glbSpooler '返回唯一的实例

End Try

End Function

'-----

Public Sub Print(ByVal str As String)

If legalInstance Then

MessageBox.Show(str)

Else

Throw New SpoolerException()

End If

End Sub

'-----

End Class









SpoolerException类



Public Class SpoolerException

Inherits Exception

Private mesg As String

'---------

Public Sub New()

MyBase.New()

mesg = "只能创建一个实例!"

End Sub

'---------

Public Overrides ReadOnly Property Message() As String

Get

Message = mesg

End Get

End Property

End Class



使用单件模式



Private Spl As Spooler

Private Sub ErrorBox(ByVal mesg As String)

MessageBox.Show(mesg, "Spooler Error", MessageBoxButtons.OK)

End Sub

Private Sub btGetSpooler_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btGetSpooler.Click

Try

Spl = Spooler.getSpooler

TextBox1.Text = "创建实例!"

Catch ex As Exception

ErrorBox("实例已经创建,并且只能创建一个实例!")

End Try

End Sub



Private Sub Print_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Print.Click

Try

Spl.Print("实例已经创建,并且你单击了按钮!")

Catch ex As Exception

ErrorBox("没有创建实例,不能执行!")

End Try

End Sub



运行



如图:






当点击”创建实例”按钮时,调用Spooler 类的getSpooler方法,试图创建实例。在Spooler的构造函数中,定义了Spool_counter 变量,这个变量用于计算Spooler实例的数量,如果为0(即还未创建Spooler实例),则创建一个Spooler实例并保存。然后增加计数器的值,如果再次点击”创建实例”按钮,因为Spooler实例的数量为1,则抛出异常,这样就可以控制并创建唯一的实例。

构造函数如下:

Private Sub New()

MyBase.New()

If Spool_counter = 0 Then '建立并且保存这个实例

glbSpooler = Me '保存实例

Spool_counter = Spool_counter + 1 '计数

legalInstance = True

Else

legalInstance = False

Throw New SpoolerException

End If

End Sub

可以通过修改构造函数中对Spool_counter的判断条件来控制创建Spooler实例的任意个数。这可以说是单件模式的扩充吧!:)



Private Sub New()

MyBase