Strategy Pattern V/S Decorator Pattern

后端 未结 7 1315
星月不相逢
星月不相逢 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:53

    I would say strategy pattern allows you to choose one of multiple ways to do something, or one of multiple implementations for some operation, while decorator pattern allows you to create an object as it suits your needs by using desired object's (actually its class and/or interface(s)) functionalities and their implementations (whichever you want and how many times you want in order to create needed object).

    Both are done dynamically, in other words at runtime.

    Strategy pattern example

    You are reading content of a folder. It contains plain .txt, .csv and JSON files. Call some method Read() from your IReader interface, but depending on type of the file, use appropriate implementation of Read() method. Use strategy pattern to decide which implementation.

    Decorator pattern example

    Export the result of Read() method to some XML file, but depending on the result, some Header node in XML can contain one, or more nodes and a node can differ in its content. Header may, or may not contain Date node, which may have one of several date formats; it may, or may not contain ReadDuration node, which can be represented in millisecond, seconds, or minutes (with additional node that says which unit is used); it may, or may not contain a node that represents a quantity of items read, like NumberOfItems, or NumberOfRows, or something similar.

    So some of the XML Header node examples contain:

    • Date node where date format is YYYY-MM-DD and ReadDuration node which says how many seconds it took to read the file
    • Date node where date format is DD-MM-YYYY
    • Date node where format is YYYY-MM-DD, ReadDuration node which says how many millisecnods it took to read the file and NumberOfRows node
    • ReadDuration node which says how many millisecnods it took to read the file and NumberOfRows node
    • ReadDuration node which says how many seconds it took to read the file and NumberOfRows node
    • Date node where format is YYYY-MM-DD, ReadDuration node which says how many millisecnods it took to read the file, NumberOfRows node and NumberOfItems node
    • and so on

提交回复
热议问题