Skip to content

Instantly share code, notes, and snippets.

@dfinke
Last active July 3, 2024 17:27
Show Gist options
  • Save dfinke/86070d24cf28000e161e41abb098ae4b to your computer and use it in GitHub Desktop.
Save dfinke/86070d24cf28000e161e41abb098ae4b to your computer and use it in GitHub Desktop.
PowerShell Decorator Pattern: Enhance Logger with Timestamp and Uppercase
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
@ronascentes
Copy link

That is very helpful! Thanks for sharing.

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