简体   繁体   中英

Decorator Design Pattern Ambigous

Let take simple class diagram as an example

在此输入图像描述

My Question is why do we need OptionalWrapper ? Isn't it enough that OptionalOne , OptionalTwo and OptionalThree implements Interface because all we need is the Interface type of object in the decorator classes.

OptionalWrapper is where you add a reference to the class you're decorating, and redirect all of its methods to that instance. If you don't have OptionalWrapper , then you'd need to repeat this code in each of its subclasses. In the given diagram, each one of the subclasses only needs to override the behavior they're supposed to modify.

A more concrete example: you want to add exception handling. You can do this once in the OptionalWrapper and be finished, or you can implement it in each of the three subclasses (and every new class you have that implements the interface).

1) In your example if you decide to add new behaviors in all of the decorators OptionalOne , OptionalTwo and OptionalThree then you will add a new method in Interface but that impacts CoreFunactionality . So to separate this you need one more interface/abstract class OptionalWrapper .

2) All decorators just need to deal with OptionalWrapper and do not worry about what instance it is decorating.

Here optional wrapper is your Decorator class which will be abstract in most cases. It enhances an object's responsibilities. If you add some more functionalities in your interface which need not to be implemented in your optional classes(optional1, optiona2 and etc), you'll need an abstract optional wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM