Strategy Design Pattern and Factory Method Design Pattern

后端 未结 4 740
后悔当初
后悔当初 2021-02-13 04:44

I start learning Design Patterns. Now I understand a little bit but there are quite a lot of confusions for me. What\'s the difference between Strategy DP and <

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 04:59

    Strategy is about behavior. Factory is about creation/instatation.

    Suppose you have an algorithm, to calculate a discount percentage. You can have 2 implementations of that algorithm; one for regular customers, and one for extra-ordinary good customers.
    You can use a strategy DP for this implementation: you create an interface, and 2 classes that implement that interface. In one class, you implement the regular discount-calculation algorithm, in the other class you implement the 'good customers' algorithm.

    Then, you can use a factory pattern to instantiate the class that you want. The factory method thus instantiates either the regular customer-discount algorithm, or the other implementation.

    In short: the factory method instantiates the correct class; the strategy implementation contains the algorithm that must be executed.

提交回复
热议问题