Skip to content

Instantly share code, notes, and snippets.

@dfinke
Created May 10, 2024 12:27
Show Gist options
  • Save dfinke/6c3994cff55751eedd98058dfe76d234 to your computer and use it in GitHub Desktop.
Save dfinke/6c3994cff55751eedd98058dfe76d234 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