views:

191

answers:

1

Hello!

Can anyone give a practical example of using the design patterns Composite and Chain of Responsibility together?

Thanks

A: 

A practical answer may be impossible, but I can see where you would have a composition of chains of responsibility. Here's a pythonish example:

>>> class DevelopmentPerformanceMonitor():
...   def getPerformanceMonitorHandlers():
...     return []
... 
>>> class ProductionPerformanceMonitor():
...   def getPerformanceMonitorHandlers():
...     return [check_cpu_under_load, check_available_hd]
... 
>>> class DevelopmentExceptionMonitor():
...   def getExceptionHandlers():
...     return [email_local_root, log_exception]
... 
>>> class ProductionExceptionMonitor():
...   def getExceptionHandlers():
...     return [emails_system_admin, log_exception, create_ticket]
... 
>>> class SomeSystem:
...    pm = None # Performance Monitor
...    em = None # Exception Monitor
...    def __init__(self, performance_monitor, exception_monitor):
...      pm = performance_monitor
...      em = exception_monitor
...    def on_exception(e):
...      for handler in em.getExceptionHandlers():
...        handler(e)
...    def perform_performance_monitoring(s):
...      for handler in pm.getPerformanceMonitorHandlers():
...        handler(s)

So the SomeSystem object is a composite of a performance_monitor and an exception_monitor. Each of the composites will return a series of handlers for desired chain of responsibility. Although this example is really only complicating a simpler Chains of Responsibility, where the SomeSystem could be initiated with the chains themselves. Although keeping them packaged may be helpful.

W Devauld
I've found a good example of Composite + Chain of Responsibility, in the book "Design Patterns in Java", by Steven Metsker and William Wake. You can read it at Google Books. Basically, we've got machine, lines, bays and factories. Factories are compositions of bays, and so on. At this point, we get the Composite pattern. Each element, from machines to factories, have an engineer who's responsible for the component. But, in some cases, a simple machine doesn't have an engineer, so we've got to look for its parent to find him (CoR).[]'s
Fabio Gouw