Chain-of-responsibility pattern: Difference between revisions

Content deleted Content added
fix formatting
m Clean up/General fixes, typo(s) fixed: etc) → etc.)
Line 5:
This pattern promotes the idea of [[loose coupling]].
 
The chain-of-responsibility pattern is structurally nearly identical to the [[decorator pattern]], the difference being that for the decorator, all classes handle the request, while for the chain of responsibility, exactly one of the classes in the chain handles the request. This is a strict definition of the Responsibility concept in the [[Design Patterns|GoF]] book. However, many implementations (such as loggers below, or UI event handling, or servlet filters in Java, etc.) allow several elements in the chain to take responsibility.
 
==Overview==
Line 35:
== Structure ==
=== UML class and sequence diagram ===
[[File:w3sDesign Chain of Responsibility Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the Chain of Responsibility design pattern. <ref>{{cite web|title=The Chain of Responsibility design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=b01&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>]]
 
In the above [[Unified Modeling Language|UML]] [[class diagram]], the <code>Sender</code> class doesn't refer to a particular receiver class directly.
Line 49:
 
{{wikibooks|Computer Science Design Patterns|Chain of responsibility|Chain-of-responsibility implementations in various languages}}
 
=== Java example ===
Below is an example of this pattern in Java.
Line 359 ⟶ 360:
from abc import ABCMeta, abstractmethod
from enum import Enum, auto
 
 
class LogLevel(Enum):
Line 371:
FUNCTIONAL_ERROR = auto()
ALL = auto()
 
 
class Logger:
Line 422 ⟶ 421:
"""
raise NotImplementedError("You should implement this method.")
 
 
class ConsoleLogger(Logger):
Line 432 ⟶ 430:
"""
print("Writing to console:", msg)
 
 
class EmailLogger(Logger):
Line 442 ⟶ 439:
def write_message(self, msg: str) -> None:
print(f"Sending via email: {msg}")
 
 
class FileLogger(Logger):
Line 452 ⟶ 448:
def write_message(self, msg: str) -> None:
print(f"Writing to log file: {msg}")
 
 
def main():
Line 489 ⟶ 484:
)
logger.message("OrderDispatched.", LogLevel.FUNCTIONAL_MESSAGE)
 
 
if __name__ == "__main__":