Strategy Pattern V/S Decorator Pattern

后端 未结 7 1306
星月不相逢
星月不相逢 2021-01-29 20:06

I just came across two patterns.

  1. Strategy Pattern

  2. Decorator

Strategy Pattern :-

Strategy pattern

7条回答
  •  迷失自我
    2021-01-29 20:55

    Strategy_pattern

    1. Defines a family of algorithms,
    2. Encapsulates each algorithm, and
    3. Makes the algorithms interchangeable within that family.

    Use Strategy pattern when you have to change algorithm dynamically at run time.

    Decorator

    Decorator pattern dynamically changes the functionality of an object at runtime without impacting the existing functionality of the objects.

    When to use:

    1. Add additional functionalities/responsibilities dynamically
    2. Remove functionalities/responsibilities dynamically
    3. Avoid too much of sub-classing to add additional responsibilities.

    Drawbacks:

    1. Overuse of Open Closed principle ( Open for extension and Closed for modification). Use this feature sparingly where the code is least likely changed.
    2. Too many small classes and will add maintenance overhead.

    Key difference:

    Strategy lets you change the guts of an object. Decorator lets you change the skin.

    Few more useful posts:

    When to Use the Decorator Pattern?

    Real World Example of the Strategy Pattern

    strategy by sourcemaking

提交回复
热议问题