Where is the benefit in using the Strategy Pattern?

前端 未结 8 1053
太阳男子
太阳男子 2020-12-28 10:22

I\'ve looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and call

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 10:36

    One way to look at this is when you have a variety of actions you want to execute and those actions are determined at runtime. If you create a hashtable or dictionary of strategies, you could retrieve those strategies that correspond to command values or parameters. Once your subset is selected, you can simply iterate the list of strategies and execute in succession.

    One concrete example would be calculation the total of an order. Your parameters or commands would be base price, local tax, city tax, state tax, ground shipping and coupon discount. The flexibility come into play when you handle the variation of orders - some states will not have sales tax, while other orders will need to apply a coupon. You can dynamically assign the order of calculations. As long as you have accounted for all your calculations, you can accommodate all combinations without re-compiling.

提交回复
热议问题