When do we need decorator pattern?

后端 未结 9 978
攒了一身酷
攒了一身酷 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:04

    The intent of Decorator pattern is to:

    Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. [via Head First: Design Patterns]

    The most heavy use of decorator pattern are GUIs and java.io classes. There is a free chapter of Head First: Design Patterns about decorator pattern [link] which provide some other examples:

    We’ll re-examine the typical overuse of inheritance and you’ll learn how to decorate your classes at runtime using a form of object composition. Why? Once you know the techniques of decorating, you’ll be able to give your (or someone else’s) objects new responsibilities without making any code changes to the underlying classes.

    You can also read Decorator Pattern by Example [PDF] in which decorator pattern is used in an evaluation application.

提交回复
热议问题