有时需要使用一些辅助值初始化单例类.但我们不能“发布”它的构造函数.这是什么解决方法? 注意! 重载GetInstance或设置颜色不是我的想法.颜色应仅设置一次.我想确保MyPainter仅使用
注意!
重载GetInstance或设置颜色不是我的想法.颜色应仅设置一次.我想确保MyPainter仅使用初始化颜色进行绘制.应该使用任何默认颜色.
为了更清楚,我提供了一个示例:
''' <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.