Chain-of-responsibility pattern: Difference between revisions

Content deleted Content added
Examples: Move Python example to Wikibooks
Examples: Move Crystal example to Wikibooks
Line 155:
 
{{wikibooks|Computer Science Design Patterns|Chain of responsibility|Chain-of-responsibility implementations in various languages}}
 
=== Crystal example ===
<syntaxhighlight lang="crystal">
enum LogLevel
None
Info
Debug
Warning
Error
FunctionalMessage
FunctionalError
All
end
 
abstract class Logger
property log_levels
property next : Logger | Nil
 
def initialize(*levels)
@log_levels = [] of LogLevel
 
levels.each do |level|
@log_levels << level
end
end
 
def message(msg : String, severity : LogLevel)
if @log_levels.includes?(LogLevel::All) || @log_levels.includes?(severity)
write_message(msg)
end
@next.try(&.message(msg, severity))
end
 
abstract def write_message(msg : String)
end
 
class ConsoleLogger < Logger
def write_message(msg : String)
puts "Writing to console: #{msg}"
end
end
 
class EmailLogger < Logger
def write_message(msg : String)
puts "Sending via email: #{msg}"
end
end
 
class FileLogger < Logger
def write_message(msg : String)
puts "Writing to Log File: #{msg}"
end
end
 
# Program
# Build the chain of responsibility
logger = ConsoleLogger.new(LogLevel::All)
logger1 = logger.next = EmailLogger.new(LogLevel::FunctionalMessage, LogLevel::FunctionalError)
logger2 = logger1.next = FileLogger.new(LogLevel::Warning, LogLevel::Error)
 
# Handled by ConsoleLogger since the console has a loglevel of all
logger.message("Entering function ProcessOrder().", LogLevel::Debug)
logger.message("Order record retrieved.", LogLevel::Info)
 
# Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error
logger.message("Customer Address details missing in Branch DataBase.", LogLevel::Warning)
logger.message("Customer Address details missing in Organization DataBase.", LogLevel::Error)
 
# Handled by ConsoleLogger and EmailLogger as it implements functional error
logger.message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel::FunctionalError)
 
# Handled by ConsoleLogger and EmailLogger
logger.message("Order Dispatched.", LogLevel::FunctionalMessage)
</syntaxhighlight>
 
Output
<pre>
Writing to console: Entering function ProcessOrder().
Writing to console: Order record retrieved.
Writing to console: Customer Address details missing in Branch DataBase.
Writing to Log File: Customer Address details missing in Branch DataBase.
Writing to console: Customer Address details missing in Organization DataBase.
Writing to Log File: Customer Address details missing in Organization DataBase.
Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1.
Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1.
Writing to console: Order Dispatched.
Sending via email: Order Dispatched.
</pre>
 
=== PHP example ===