Strategy Pattern in Python
Strategy Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।
Strategy Pattern क्या है?
Strategy Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।
इसका उपयोग कब करें?
- सिद्ध संरचनाओं से बार-बार आने वाली object-design समस्याएँ हल करें।
- जिम्मेदारियों को अलग करें ताकि code को बढ़ाना और test करना आसान हो।
- टीम में architecture पर चर्चा करते समय साझा design शब्दावली का उपयोग करें।
उदाहरण कोड
main.py
def regular_discount(total): return total
def member_discount(total): return total * 0.8
class Checkout:
# Strategy: inject the algorithm that is allowed to vary.
def __init__(self, discount_strategy):
self.discount_strategy = discount_strategy
def total(self, amount):
# Delegate the varying algorithm to the strategy.
return self.discount_strategy(amount)
checkout = Checkout(member_discount)
print(f"{checkout.total(15):.2f}")
अपेक्षित आउटपुट
12.00
यह कैसे काम करता है
यह उदाहरण Strategy Pattern in Python दिखाता है। कोड समझने के लिए इनपुट मान बदलें।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- Pattern की संरचना बनाए रखते हुए उदाहरण का domain बदलें।
- Pattern की तुलना सरल implementation से करें और उनके trade-off समझाएँ।
- नई implementation जोड़ने से पहले प्रत्येक participant के लिए test लिखें।