powershell - 测试单例初始化并抛出适当的异常
问题描述
我正在继续尝试使用 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) {
解决方案
推荐阅读
- neo4j - 当 Neo4j 程序从 Neo4j 浏览器调用但不是从 cypher-shell 调用时,OOME 失败后重试
- jupyter-notebook - 在 jupyter notebook 中使用 plotly python 绘制具有不等热图的交互式树状图
- ruby-on-rails - ActionView::Template::Error: 在组或文件中运行 rspec 时
- android-fragments - 如何在片段中保留 Recycler View 内容和滚动位置?
- html - 突出显示 Web 文档的各个部分
- elasticsearch - 使用转换的 Elasticsearch 以实体为中心的索引
- google-colaboratory - 如何处理运行时间很长的细胞
- python - 相机在Opencv中看到时如何计算连接
- python - 为什么我的 DataFrame 在使用 df.to_csv() 和 df = pd.read_csv() 操作后会变大?
- javascript - 我可以为另一个 AWS 账户中的用户池发送 DescribeUserPoolClient 命令吗