Docs

Design Patterns — Fast Recall (Python)

Strategy — swap the algorithm at runtime


  • What: define a family of interchangeable algorithms and pick one on the fly.
  • Why / when: the same task has multiple approaches — payment methods, sort orders, discount rules — chosen by config/user.
  • Kills: the giant `if/elif` on a 'type' flag; add a new strategy without editing existing code (Open/Closed).
  • Python truth: a strategy is just a function — pass it as an argument, no interface class needed.
1def pay_card(amt): print("card", amt) 2def pay_upi(amt): print("upi", amt) 3 4def checkout(amt, strategy): # inject the algorithm 5 strategy(amt) 6 7checkout(100, pay_card) # card 100 8checkout(50, pay_upi) # upi 50