Skip to content

Instantly share code, notes, and snippets.

@dfinke
Last active July 3, 2024 17:28
Show Gist options
  • Save dfinke/a5ee145875ad61a88e0cc27f81899b9d to your computer and use it in GitHub Desktop.
Save dfinke/a5ee145875ad61a88e0cc27f81899b9d to your computer and use it in GitHub Desktop.
PowerShell implementation of the Observer Pattern with a Clock Timer example, featuring Digital and Analog clocks.
class Subject {
hidden [System.Collections.ArrayList]$observers
Subject() {
$this.observers = New-Object System.Collections.ArrayList
}
Attach([Observer]$o) { $this.observers.Add($o) }
Detach([Observer]$o) { $this.observers.Remove($o) }
Notify() {
foreach($observer in $this.observers) {
$observer.Update($this)
}
'' | out-host
}
}
class Observer {
Update([Subject]$subject) {}
}
class ClockTimer : Subject {
hidden [datetime]$currentTime
[int] GetHour() { return $this.currentTime.Hour }
[int] GetMinute() { return $this.currentTime.Minute }
[int] GetSecond() { return $this.currentTime.Second }
[datetime] GetFull() { return $this.currentTime}
Tick() {
$this.currentTime = Get-Date
$this.Notify()
}
StartTimer() {
while($true) {
$this.Tick()
Start-Sleep 1
}
}
}
class DigitalClock : Observer {
Update([Subject]$subject) {
$hour = $subject.GetHour()
$minute = $subject.GetMinute()
$second = $subject.GetSecond()
"[Digital Clock] {0}:{1}:{2}" -f $hour, $minute, $second | Out-Host
}
}
class AnalogClock : Observer {
Update([Subject]$subject) {
"[Analog Clock] {0}" -f $subject.GetFull() | Out-Host
}
}
$timer = [ClockTimer]::new()
$digitalClock = [DigitalClock]::new()
$analogClock = [AnalogClock]::new()
$timer.Attach($digitalClock)
$timer.Attach($analogClock)
$timer.StartTimer()
@dfinke
Copy link
Author

dfinke commented May 23, 2024

[Digital Clock] 9:42:23
[Analog Clock] Thu 05 23 2024 9:42:23 AM

[Digital Clock] 9:42:24
[Analog Clock] Thu 05 23 2024 9:42:24 AM

[Digital Clock] 9:42:25
[Analog Clock] Thu 05 23 2024 9:42:25 AM

[Digital Clock] 9:42:26
[Analog Clock] Thu 05 23 2024 9:42:26 AM

[Digital Clock] 9:42:27
[Analog Clock] Thu 05 23 2024 9:42:27 AM

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