Strategy Design Pattern and Factory Method Design Pattern

后端 未结 4 731
后悔当初
后悔当初 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:49

    Strategies incapsulate different behaviors behind the same interface. You instantiate Strategies with new operator. For example (the same business case as Frederik suggested):

    DiscountCalculator calc = new GoogCustomerDiscountCalculator();
    Integer discount = calc.calculate();
    

    Factory Method incapsulates instantiation mechanism of some other interface (maybe a Strategy, but maybe something else). For example:

    DiscountFactory factory = new DiscountFactory();
    DiscountCalculator calc = factory.getDiscountCalculator();
    Integer discount = calc.calculate();
    

    Strategy pattern is often used together with Factory Method, while Factory Method is often used for instantiation of other stereotypes, not only Strategies.

提交回复
热议问题