Skip to content

Instantly share code, notes, and snippets.

@chadmando
Forked from dfinke/CeilingFan.ps1
Created May 14, 2024 16:22
Show Gist options
  • Save chadmando/5f080f4e1164bbb8e3dc30fd58b036d8 to your computer and use it in GitHub Desktop.
Save chadmando/5f080f4e1164bbb8e3dc30fd58b036d8 to your computer and use it in GitHub Desktop.
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
<#
Allow an object to alter its behavior when its internal state changes.
The object will appear to change its class.
The State pattern puts each branch of the conditional in a separate class.
This lets you treat the object's state as an object in its own right
that can vary independently from other objects
#>
class CeilingFanState {
Change([CeilingFan] $ceilingFan) {
throw "not implemented"
}
}
class CeilingFanOff : CeilingFanState {
Change([CeilingFan] $context) {
$context.State = [CeilingFanLow]::new()
"Change state from Off to Low." | Out-Host
}
}
class CeilingFanLow: CeilingFanState {
Change([CeilingFan] $context) {
$context.State = [CeilingFanMedium]::new()
"Change state from Low to Medium." | Out-Host
}
}
class CeilingFanMedium: CeilingFanState {
Change([CeilingFan] $context) {
$context.State = [CeilingFanHigh]::new()
"Change state from Medium to High." | Out-Host
}
}
class CeilingFanHigh: CeilingFanState {
Change([CeilingFan] $context) {
$context.State = [CeilingFanLow]::new()
"Change state from High to Off." | Out-Host
}
}
class CeilingFan {
$State
CeilingFan ([CeilingFanState] $state) { $this.State = $state }
Pull() { $this.State.Change($this) }
}
$ceilingFan = [CeilingFan]::new([CeilingFanOff]::new())
$ceilingFan.Pull()
$ceilingFan.Pull()
$ceilingFan.Pull()
$ceilingFan.Pull()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment