When do we need decorator pattern?

后端 未结 9 855
攒了一身酷
攒了一身酷 2020-12-02 18:32

When is it necessary to use the decorator pattern? If possible, give me a real world example that is well-suited for the pattern.

相关标签:
9条回答
  • 2020-12-02 19:27

    You asked for a real-world example, so here you go: download (or browse) DonsProxy from github:

    git://github.com/DonBranson/DonsProxy.git

    DonsProxy basically uses a WireTap pattern to let you watch or extract HTTP traffic, plus it lets you modify the connection behavior to simulate suboptimal connections. I use the Decorator pattern to modify channels based on user options. Command-line or GUI options (dependinvg on which View they're using) allows latency injection and bandwidth injection, among other things. When they inject latency, that adds the LatencyDecorator to the channel; if they throttle the bandwidth, that adds the ThrottleDecorator to the channel. Since this use a decorator pattern, they can mix-and-match behavior to their heart's content.

    0 讨论(0)
  • 2020-12-02 19:28

    Two real-life examples:

    The item upgrading systems in Diablo 2 and Final Fantasy 7. Weapons and armor have sockets or slots. During the game, the player put upgrades (gems, runes or materia) into those slots. Each upgrade has an individual effect (say, 8 points fire damage or 10% mana leech). So when you swing your sword, it does its base damage plus the damage added by each upgrade you've added. This matches the decorator pattern extremely closely.

    0 讨论(0)
  • 2020-12-02 19:30

    Have a look at the Fowler description; it gives a concrete example relating to books/videos and a decorator "borrowable", you can find it here.

    0 讨论(0)
提交回复
热议问题