Why would I ever use a Chain of Responsibility over a Decorator?

后端 未结 11 1927
[愿得一人]
[愿得一人] 2020-12-04 12:58

I\'m just reading up on the Chain of Responsibility pattern and I\'m having trouble imagining a scenario when I would prefer its use over that of decorator.

What do

11条回答
  •  猫巷女王i
    2020-12-04 13:44

    Decorator

    1. Decorator pattern allows behaviour to be added to an individual object dynamically.

    2. It provides a flexible alternative to sub classing for extending functionality. Even though it uses inheritance, it inherit from Lowest Common Denominator ( LCD ) interface.

    UML diagram for Decorator

    Consequences:

    1. With decoration it is also possible to remove the added functionalities dynamically.
    2. Decoration adds functionality to objects at runtime which would make debugging system functionality harder.

    Useful links:

    When to Use the Decorator Pattern?

    Decorator_pattern from wikipedia

    decorator from sourcemaking

    Chain of responsibility:

    Chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain

    UML Diagram

    This pattern is more effective when:

    1. More than one object can handle a command
    2. The handler is not known in advance
    3. The handler should be determined automatically
    4. It’s wished that the request is addressed to a group of objects without explicitly specifying its receiver
    5. The group of objects that may handle the command must be specified in a dynamic way

    Useful links:

    Chain-of-responsibility_pattern from wikipedia

    chain-of-responsibility-pattern from oodesign

    chain_of_responsibility from sourcemaking

    Real world example : In a company, a designated role have particular limits to process purchase request. If person with a designated role does not have enough power to approve purchase bill, he will forward the command/request to his successor, who have more power. This chain will continue until the command is processed.

提交回复
热议问题