Skip to content

Instantly share code, notes, and snippets.

@chadmando
Forked from dfinke/CeilingFan.ps1
Created May 14, 2024 16:22

Revisions

  1. @dfinke dfinke created this gist May 10, 2024.
    59 changes: 59 additions & 0 deletions CeilingFan.ps1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    <#
    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()