Singleton 提供一种方法使得某一特定类型存在一个,并且只能是一个对象。它可
能是最简单的模式了。Singleton 应用的一个重要方面是提供一个全局的存取点。
Singleton 是C 里面全局变量的一个替代方法。
实例代码:
final
class
Singleton
...
{
private static Singleton s = new Singleton(47);
private int i;
private Singleton(int x) ...{ i = x; }
public static Singleton getReference() ...{
return s;
}
public int getValue() ...{ return i; }
public void setValue(int x) ...{ i = x; }
}
private static Singleton s = new Singleton(47);
private int i;
private Singleton(int x) ...{ i = x; }
public static Singleton getReference() ...{
return s;
}
public int getValue() ...{ return i; }
public void setValue(int x) ...{ i = x; }
}
Public
NotInheritable
Class Singleton
Class Singleton
Private Shared s As Singleton = New Singleton(47)
Private i As Integer = 0
Private Sub New()Sub New(ByVal x As Integer)
i = x
End Sub
Public Shared Function GetReference()Function GetReference()
Return s
End Function
Public Function GetValue()Function GetValue() As Integer
Return i
End Function
Public Sub SetValue()Sub SetValue(ByVal x As Integer)
i = x
End Sub
End Class
Private Shared s As Singleton = New Singleton(47)
Private i As Integer = 0
Private Sub New()Sub New(ByVal x As Integer)
i = x
End Sub
Public Shared Function GetReference()Function GetReference()
Return s
End Function
Public Function GetValue()Function GetValue() As Integer
Return i
End Function
Public Sub SetValue()Sub SetValue(ByVal x As Integer)
i = x
End Sub
End Class