您现在的位置: 无忧电子商务网 >> 信息学院 >> 程序开发 >> asp.net >> 正文

设计模式之单件模式(Singleton Pattern )

作者:作者:未…    信息学院来源:网络收集    点击数:    更新时间:2006-8-28 我要参与讨论

  单件模式

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(&

[1] [2] 下一页

在google里搜索更多设计模式之单件模式(Singleton Pattern )

Google
Web www.51ec.org
  • 上一篇信息学院:

  • 下一篇信息学院:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
    我来说两句 对此文章发表了评论
      昵 称: *必填    ·注册用户·
      评 分: 1分 2分 3分 4分 5分     严禁发表危害国家安全、政治、黄色淫秽等内容的评论,用户需对自己在使用本网站服务过程中的行为承担法律责任。本站管理员有权保留或删除评论内容,评论内容只代表机友个人观点,与本网站立场无关。  
    评 论
    内 容

     
    评论列表 (最新 评论仅限网友观点!)

    供求信息




    | 设为首页 | 加入收藏 | 关于我们 | 广告服务 | 联系方式 | 友情链接 | 版权申明