Skip to content

Instantly share code, notes, and snippets.

@dfinke
Last active July 3, 2024 17:29
Show Gist options
  • Save dfinke/570e972a7297be0fd394be8386b87c2c to your computer and use it in GitHub Desktop.
Save dfinke/570e972a7297be0fd394be8386b87c2c to your computer and use it in GitHub Desktop.
Composite Pattern: Simplifies client code by treating individual objects and compositions uniformly, making it easier to work with complex structures
class Employee {
$name
$dept
$salary
hidden [Employee[]]$subordinates = @()
Employee($name, $dept, $salary) {
$this.name = $name
$this.dept = $dept
$this.salary = $salary
}
Add([Employee]$e) {
$this.subordinates += $e
}
[Employee[]] GetSubordinates() {
return $this.subordinates
}
[string] ToString() {
return "[{0}] {1}: {2:C0}" -f $this.dept, $this.name, $this.salary
}
}
. .\Employee.ps1
$CEO = [Employee]::new("John","CEO", 30000)
$HeadSales = [Employee]::new("Robert","Head Sales", 20000)
$HeadMarketing = [Employee]::new("Michel","Head Marketing", 20000)
$clerk1 = [Employee]::new("Laura","Marketing", 10000)
$clerk2 = [Employee]::new("Bob","Marketing", 10000)
$salesExecutive1 = [Employee]::new("Richard","Sales", 10000)
$salesExecutive2 = [Employee]::new("Rob","Sales", 10000)
$CEO.Add($HeadSales)
$CEO.Add($HeadMarketing)
$HeadSales.Add($salesExecutive1)
$HeadSales.Add($salesExecutive2)
$HeadMarketing.Add($clerk1)
$HeadMarketing.Add($clerk2)
"$CEO"
foreach($headEmployee in $CEO.GetSubordinates()) {
"`t$headEmployee"
foreach ($employee in $headEmployee.GetSubordinates()) {
"`t`t$employee"
}
}
@dfinke
Copy link
Author

dfinke commented May 16, 2024

[CEO] John: $30,000
        [Head Sales] Robert: $20,000
                [Sales] Richard: $10,000
                [Sales] Rob: $10,000
        [Head Marketing] Michel: $20,000
                [Marketing] Laura: $10,000
                [Marketing] Bob: $10,000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment