Is there a correct/best/any way to make a singleton class using the class constructs in PowerShell 5.0? I've tried something like this:
class ScannerGeometry
{
[int] $EEprom; # read eeprom
# ....
ScannerGeometry()
{
# ... fetch calibration from instrument
}
[ScannerGeometry] Instance() {
if ($this -eq $null)
{
$this = [ScannerGeometry]::new()
}
return $this
}
}
And assigning it with something like:
$scanner = [ScannerGeometry]::Instance()
Alas, I receive a runtime error of Method invocation failed because [ScannerGeometry] does not contain a method named 'Instance'.
Also, may one make the constructor(or any other method) private in PS5 classes?
Your method is visible like this since it is not static:
[ScannerGeometry]::new() | set x
PS C:\Work> $x | gm
TypeName: ScannerGeometry
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Instance Method ScannerGeometry Instance()
ToString Method string ToString()
EEprom Property int EEprom {get;set;}
You need to use keyword static. In that case $this is invalid so you have to change code a bit. Here is the code:
class ScannerGeometry
{
[int] $EEprom; # read eeprom
static [ScannerGeometry] Instance() {
return [ScannerGeometry]::new()
}
}
EDIT
Ok, here is the working code:
class ScannerGeometry
{
[int] $EEprom # read eeprom
static [ScannerGeometry] $instance
static [ScannerGeometry] GetInstance() {
if ([ScannerGeometry]::instance -eq $null) { [ScannerGeometry]::instance = [ScannerGeometry]::new() }
return [ScannerGeometry]::instance
}
}
$s = [ScannerGeometry]::GetInstance()
How about this ?
class ScannerGeometry
{
[int] $EEprom; # read eeprom
# ....
ScannerGeometry()
{
# ... fetch calibration from instrument
}
[ScannerGeometry] Instance() {
if ($this -eq $null)
{
$this = [ScannerGeometry]::new()
}
return $this
}
}
$scangeo = [ScannerGeometry]::new().Instance()
PS : the code only gives no error, I'm completely clueless about the singleton context :(
Source : HSGB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With