-
-
Save ronascentes/b030fa819a72caeac5fcb8c4cc9c156a to your computer and use it in GitHub Desktop.
Demonstrates the implementation of the Mediator Design Pattern in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Define an object that encapsulates how a set of objects interact. | |
Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. | |
#> | |
class ChatMediator { | |
$users | |
ChatMediator() { | |
$this.users = New-Object System.Collections.ArrayList | |
} | |
AddUser($user) { | |
$this.users.add($user) | |
} | |
RemoveUser($user) { | |
$this.users.remove($user) | |
} | |
SendMessage($msg, $user) { | |
foreach ($targetUser in $this.users) { | |
# message should not be received by the user sending it | |
if ($targetUser -ne $user) { | |
$targetUser.receive($msg) | |
} | |
} | |
} | |
} | |
class User { | |
$mediator | |
$name | |
User($mediator, $name) { | |
$this.mediator = $mediator | |
$this.name = $name | |
} | |
Send($msg) { | |
"$($this.name): Sending Message: $msg " | Out-Host | |
$this.mediator.SendMessage($msg, $this) | |
} | |
Receive($msg) { | |
"$($this.name): Received Message: $msg " | Out-Host | |
} | |
} | |
$script:mediator = $null | |
function New-ChatUser { | |
param($name) | |
# Singleton - Lazy Evaluation | |
if ($null -eq $script:mediator) { | |
$script:mediator = [ChatMediator]::new() | |
} | |
$chatUser = [User]::new($mediator, $name) | |
$mediator.AddUser($chatUser) | |
$chatUser | |
} | |
$John = New-ChatUser John | |
$Lisa = New-ChatUser Lisa | |
$Maria = New-ChatUser Maria | |
$David = New-ChatUser David | |
'' | |
$John.Send("Hello everyone") | |
$script:mediator.RemoveUser($John) | |
"`nUser John has left the chat room`n" | |
$David.Send("Hi") | |
'' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment