首页 > 解决方案 > 测试单例初始化并抛出适当的异常

问题描述

我正在继续尝试使用 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 还是 0 的计数,但我不能从静态方法引用非静态属性,所以除非静态 $Initialized 属性的笨拙方法,什么是解决方案?

编辑:呃。希望这对其他人有帮助。不要像这样测试价值,测试存在。

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

标签: powershellsingleton

解决方案


推荐阅读