Python डिज़ाइन पैटर्न

Factory Method Pattern in Python

Factory Method Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।

Factory Method Pattern क्या है?

Factory Method Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।

इसका उपयोग कब करें?

  • सिद्ध संरचनाओं से बार-बार आने वाली object-design समस्याएँ हल करें।
  • जिम्मेदारियों को अलग करें ताकि code को बढ़ाना और test करना आसान हो।
  • टीम में architecture पर चर्चा करते समय साझा design शब्दावली का उपयोग करें।

उदाहरण कोड

कोड चलाएँ →
main.py
class EmailNotification:
    # Factory Method: creation is separated from object usage.
    def send(self, message):
        return f"Email: {message}"


class SmsNotification:
    def send(self, message):
        return f"SMS: {message}"


def create_notification(channel):
    # Centralize the concrete-class selection.
    factories = {"email": EmailNotification, "sms": SmsNotification}
    return factories[channel]()


notification = create_notification("email")
print(notification.send("Hello"))

अपेक्षित आउटपुट

Email: Hello

यह कैसे काम करता है

यह उदाहरण Factory Method Pattern in Python दिखाता है। कोड समझने के लिए इनपुट मान बदलें।

मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।

अभ्यास के कार्य

बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।

  1. Pattern की संरचना बनाए रखते हुए उदाहरण का domain बदलें।
  2. Pattern की तुलना सरल implementation से करें और उनके trade-off समझाएँ।
  3. नई implementation जोड़ने से पहले प्रत्येक participant के लिए test लिखें।
Python IDE में चलाएँ →