测试单例初始化并引发适当的异常

时间:2019-11-26 11:15:42

标签: powershell singleton

我将继续尝试使用PowerShell类来解决单例实现,并且现在在处理异常方面遇到问题。 我的测试单例需要使用要处理的文件列表进行首次初始化,并且所有后续引用都应没有参数,因为我不想再处理文件,只需引用最初处理的内容即可。为此,我有这个...

class TestClass {
    # Properties
    [collections.arrayList]$Files = [collections.arrayList]::New()
    static [TestClass] $instance = $null

    # Constructor
    TestClass([string[]]$filePaths){
        foreach ($path in $filePaths) {
            $this.Files.Add("$($path): Processed")
        }
    }

    [void] ListFiles() {
        foreach ($processedFile in $this.Files) {
            Write-Host "$processedFile!"
        }
    }

    # Singleton Methods
    static [TestClass] GetInstance() {
        if ([TestClass]::Instance -ne $null) {
            $caller = (Get-PSCallStack)[-1]
            throw "Px Tools Exception: Singleton must be initialized ($caller)"
        } 
        return [TestClass]::Instance
    }
    static [TestClass] GetInstance([string[]]$filePaths) {
        if ([TestClass]::Instance -eq $null) {
            [TestClass]::Instance = [TestClass]::New($filePaths)
        } else {
            $caller = (Get-PSCallStack)[-1]
            throw "Px Tools Exception: Singleton cannot be reinitialized ($caller)"
        }
        return [TestClass]::Instance
    }
} 

正确完成的第一个初始化工作即

$firstInstance = [TestClass]::GetInstance($unprocessedFiles)
$firstInstance.ListFiles()

将初始化单例并列出文件。因此条件if ([TestClass]::Instance -eq $null)起作用。

此外,如果我尝试像这样重新初始化

$firstInstance = [TestClass]::GetInstance($unprocessedFiles)
$secondInstance = [TestClass]::GetInstance($unprocessedFiles)

我得到了合适的

  

例外:无法重新初始化单例

但是,如果我是第一个引用而没有要处理的文件,像这样...

$firstInstance = [TestClass]::GetInstance()

我没有错误。那么,为什么if ([TestClass]::Instance -eq $null)似乎可以正常工作,而if ([TestClass]::Instance -ne $null)却不能正常工作?而且,有没有更好的方法来解决这个问题?我以为也许可以测试$ Files属性(无论是$ null还是Count为0),但是我无法从静态方法中引用非静态属性,因此除非使用静态$ Initialized属性的混搭方法,否则解决方案?

编辑:Du。希望这可以帮助其他人。像这样不要测试价值,测试存在性。

if (-not [TestClass]::Instance) {

0 个答案:

没有答案