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

后端 未结 11 1925
[愿得一人]
[愿得一人] 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条回答
  •  无人及你
    2020-12-04 13:19

    The difference between these patterns is not related to when or how the chain can be broken (which assumes a chain) or in when the extra behaviour is executed. They are related in that they both use composition in favour of inheritance to provide a more flexible solution.

    The key difference is that a decorator adds new behaviour that in effect widens the original interface. It is similar to how normal extension can add methods except the "subclass" is only coupled by a reference which means that any "superclass" can be used.

    The COR pattern can modify an existing behaviour which is similar to overriding an existing method using inheritance. You can choose to call super.xxx() to continue up the "chain" or handle the message yourself.

    So the difference is subtle but an example of a decorator should help:

    interface Animal
    {
        Poo eat(Food food);
    }
    
    class WalkingAnimal implements Animal
    {
        Animal wrapped;
        WalkingAnimal(Animal wrapped)
        {
            this.wrapped = wrapped;
        }
    
        Position walk(Human walker)
        {
        };
    
        Poo eat(Food food)
        {
          return wrapped.eat(food);
        }
    }
    
    class BarkingAnimal implements Animal
    {
        Animal wrapped;
        BarkingAnimal(Animal wrapped)
        {
            this.wrapped = wrapped;
        }
    
        Noise bark()
        {
        };
    
        Poo eat(Food food)
        {
            bark();
            return wrapped.eat();
        }
    }
    

    You can see that we can compose a walking, barking animal... or in fact add the ability to bark to any animal. To use this extra behaviour directly we would need to keep a reference to the BarkingAnimal decorator.

    All BarkingAnimal's also bark once before eating which has changed existing functionality and so is similar to a COR. But the intent is not the same as COR i.e. to find one Animal of many that will eat the food. The intent here is to modify the behaviour.

    You could imagine a COR being applied to find a human that will take the animal for a walk. This could be implemented as a linked list like chained above or as an explicit List... or whatever.

    Hope this is reasonably clear!

    John

提交回复
热议问题