CS FundamentalsHardCognizant · Capgemini pattern

A notification system has a base Notifier.send(message) and wrappers SMSDecorator, SlackDecorator that each wrap a Notifier and add their own channel's send on top of the wrapped one's send, all implementing the same Notifier interface. How is this different from simply subclassing Notifier into SMSNotifier and SlackNotifier?

  1. A. There is no real difference; both approaches scale identically as channels are added
  2. B. Subclassing allows runtime combination but Decorator only works with a single fixed channel
  3. C. Decorator requires modifying the Notifier interface for every new channel added
  4. D. Decorator lets behaviours be combined at runtime in any combination (e.g. SMS + Slack together by nesting wrappers) without creating a new subclass for every combination; static subclassing would need a separate class for each combination (SMSAndSlackNotifier, etc.), which grows combinatorially

Correct answer: D. Decorator lets behaviours be combined at runtime in any combination (e.g. SMS + Slack together by nesting wrappers) without creating a new subclass for every combination; static subclassing would need a separate class for each combination (SMSAndSlackNotifier, etc.), which grows combinatorially

Decorator's main benefit over subclassing is avoiding a combinatorial explosion of subclasses: wrapping a base Notifier in several decorators composes behaviours dynamically, while inheritance would need one subclass per combination of channels.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic