Powershell Factory Pattern as static method

Viewed 257

I am looking to implement a tool that can manage files with a variety of locations; local files, UNC path files, files hosted on AWS, files hosted on a Synology NAS, etc. This will be done in PS 5.1 using classes and a number of specific patterns.

My thinking is I need a base path type, that has a property for the path itself. Then I need classes for UNC paths, local paths, AWS paths etc. that inherit form the base Path class. Then I can have a Copy class that handles the copy differently depending on the method signature. So UNC > UNC is handled differently from AWS > UNC. So, Strategy Pattern.

As for the path types, this seems like a place for the Factory Pattern. And every single example I have found on the internet for the Factory Pattern, in PowerShell, involves a dedicated Factory class. But it seems to me that logically, the Factory to create Path derivatives could/should be part of the Path class itself, as a static method. I searched on static factory method, and the concept is well documented for other languages, but not PowerShell. So I decided to just try it. To that end, I have this as a proof of concept...

class pxPath {
    hidden $_path
    
    pxPath () {}
    pxPath ([string]$path) {
        $this._path = $path
    }

    static [pxPath] Factory ([String]$path) {
        [pxPath]$newPath = [uncFileSystem]::new($path)

        return $newPath
    }
}

class uncFileSystem : pxPath {
    
    uncFileSystem ([String]$path) : base ([String]$path) {
    }
}

$testPath = [pxPath]::Factory('\\Server\folder\file.txt')
$testPath.getType().FullName
$testPath._path

It doesn't have the multiple derived types needed for the Strategy Pattern, it just creates the one derived type. But it proves that a Factory as static method works.

My question is, is there some argument against this that I am not seeing, that explains why I have never seen an example like this for PowerShell? It makes SO much sense to me, and yet I have never seen it done, which really gives me pause.

0 Answers
Related