.net - 如何初始化单例?

标签 .net vb.net singleton

有时需要用一些辅助值来初始化单例类。但是我们不能为它“发布”一个构造函数。解决方法是什么?

注意! 重载 GetInstance 或设置颜色不是我的主意。颜色应该只设置一次。我想确保 MyPainter 使用初始化颜色绘制ONLY任何默认颜色都应该使用。

为了更清楚,我提供了一个示例:

''' <summary>
''' Singleton class MyPainter
''' </summary>
Public Class MyPainter
  Private Shared _pen As Pen
  Private Shared _instance As MyPainter = Nothing

  Private Sub New()
  End Sub

  ''' <summary>
  ''' This method should be called only once, like a constructor!
  ''' </summary>
  Public Shared Sub InitializeMyPainter(ByVal defaultPenColor As Color)
    _pen = New Pen(defaultPenColor)
  End Sub


  Public Shared Function GetInstance() As MyPainter
    If _instance Is Nothing Then
      _instance = New MyPainter
    End If

    Return _instance
  End Function

  Public Sub DrawLine(ByVal g As Graphics, ByVal pointA As Point, ByVal pointB As Point)
    g.DrawLine(_pen, pointA, pointB)
  End Sub

End Class

谢谢。

最佳答案

如果你只想在创建时初始化它一次,为什么不通过调用某些方法在构造函数中执行此操作,这将从某处提取参数?如果此初始化将被多次调用 - 将其转换为单独的方法,如 setOptions。

关于.net - 如何初始化单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687387/

相关文章:

html - 从Youtube VB.NET获取第一个视频

java - java中的单例

java - 单例线程安全 SAX 解析器实例

javascript 无效的正则表达式 无效的组

c# - 任务并行库 (TPL) 是否处理竞争条件

c# - 如何在 dotnet core 3 中使用依赖项在启动时调用自定义服务?

VB.Net 清除或重置背景颜色?

.net - WPF 调整窗口大小

vb.net - 如何在 vb.net 中引用另一个类中的类变量

c++ - 如何使用 boost::call_once 在 Linux 上用 C++ 设计单例类?