Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell 5 classes and singleton

Tags:

powershell

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?

like image 998
Mark Rasmussen Avatar asked Jul 25 '26 06:07

Mark Rasmussen


2 Answers

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()
like image 175
majkinetor Avatar answered Jul 27 '26 20:07

majkinetor


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

like image 42
sodawillow Avatar answered Jul 27 '26 21:07

sodawillow