Last active
July 30, 2024 13:54
-
-
Save dfinke/86070d24cf28000e161e41abb098ae4b to your computer and use it in GitHub Desktop.
PowerShell Decorator Pattern: Enhance Logger with Timestamp and Uppercase
This file contains hidden or 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
class Logger { | |
log($message) { # Define a method called "log" that takes a message as input | |
$message | Out-Host # Output the message to the console | |
} | |
} | |
class TimeStampingLogger : Logger { # Define a class called "TimeStampingLogger" that inherits from "Logger" | |
$logger # Declare a variable called "logger" | |
TimeStampingLogger($logger) { # Define a constructor that takes a "logger" as input | |
$this.logger = $logger # Assign the input "logger" to the class variable "logger" | |
} | |
log($message) { # Override the "log" method from the base class | |
$now = Get-Date # Get the current date and time | |
$this.logger.log("$now : $message") # Call the "log" method of the base class and prepend the timestamp to the message | |
} | |
} | |
class UpperLogger : Logger { # Define a class called "UpperLogger" that inherits from "Logger" | |
$logger # Declare a variable called "logger" | |
UpperLogger($logger) { # Define a constructor that takes a "logger" as input | |
$this.logger = $logger # Assign the input "logger" to the class variable "logger" | |
} | |
log($message) { # Override the "log" method from the base class | |
$this.logger.log($message.ToUpper()) # Call the "log" method of the base class and convert the message to uppercase | |
} | |
} | |
$message = "Hello World" # Define a variable called "message" and assign it the value "Hello World" | |
$logger = [Logger]::new() # Create an instance of the "Logger" class and assign it to the variable "logger" | |
$logger.log($message) # Call the "log" method of the "logger" instance with the "message" as input | |
$logger = [UpperLogger]::new([TimeStampingLogger]::new([Logger]::new())) # Create an instance of the "UpperLogger" class with a nested instance of "TimeStampingLogger" and a "Logger" instance as inputs, and assign it to the variable "logger" | |
$logger.log($message) # Call the "log" method of the "logger" instance with the "message" as input | |
$logger = [TimeStampingLogger]::new([Logger]::new()) # Create an instance of the "TimeStampingLogger" class with a "Logger" instance as input, and assign it to the variable "logger" | |
$logger.log($message) # Call the "log" method of the "logger" instance with the "message" as input |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That is very helpful! Thanks for sharing.