Skip to content

Instantly share code, notes, and snippets.

@dfinke
Created June 21, 2024 14:06
Show Gist options
  • Save dfinke/c2615c4edc4df4886836153dd207815d to your computer and use it in GitHub Desktop.
Save dfinke/c2615c4edc4df4886836153dd207815d to your computer and use it in GitHub Desktop.
Demonstrates the implementation of the Mediator Design Pattern in PowerShell
<#
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")
''
@dfinke
Copy link
Author

dfinke commented Jun 21, 2024

John: Sending Message: Hello everyone
Lisa: Received Message: Hello everyone
Maria: Received Message: Hello everyone
David: Received Message: Hello everyone

User John has left the chat room

David: Sending Message: Hi
Lisa: Received Message: Hi
Maria: Received Message: Hi

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