Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ronascentes/3d0d3e68a69549e2835c61d55f6f608e to your computer and use it in GitHub Desktop.
Save ronascentes/3d0d3e68a69549e2835c61d55f6f608e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment