Evgenii Legotckoi
Sept. 24, 2018, 8:43 p.m.

Example - Factory method in Python

An example of a factory method in the Python programming language


  1. """
  2. Define an interface for creating an object, but let subclasses decide
  3. which class to instantiate. Factory Method lets a class defer
  4. instantiation to subclasses.
  5. """
  6.  
  7. import abc
  8.  
  9.  
  10. class Creator(metaclass=abc.ABCMeta):
  11. """
  12. Declare the factory method, which returns an object of type Product.
  13. Creator may also define a default implementation of the factory
  14. method that returns a default ConcreteProduct object.
  15. Call the factory method to create a Product object.
  16. """
  17.  
  18. def __init__(self):
  19. self.product = self._factory_method()
  20.  
  21. @abc.abstractmethod
  22. def _factory_method(self):
  23. pass
  24.  
  25. def some_operation(self):
  26. self.product.interface()
  27.  
  28.  
  29. class ConcreteCreator1(Creator):
  30. """
  31. Override the factory method to return an instance of a
  32. ConcreteProduct1.
  33. """
  34.  
  35. def _factory_method(self):
  36. return ConcreteProduct1()
  37.  
  38.  
  39. class ConcreteCreator2(Creator):
  40. """
  41. Override the factory method to return an instance of a
  42. ConcreteProduct2.
  43. """
  44.  
  45. def _factory_method(self):
  46. return ConcreteProduct2()
  47.  
  48.  
  49. class Product(metaclass=abc.ABCMeta):
  50. """
  51. Define the interface of objects the factory method creates.
  52. """
  53.  
  54. @abc.abstractmethod
  55. def interface(self):
  56. pass
  57.  
  58.  
  59. class ConcreteProduct1(Product):
  60. """
  61. Implement the Product interface.
  62. """
  63.  
  64. def interface(self):
  65. pass
  66.  
  67.  
  68. class ConcreteProduct2(Product):
  69. """
  70. Implement the Product interface.
  71. """
  72.  
  73. def interface(self):
  74. pass
  75.  
  76.  
  77. def main():
  78. concrete_creator = ConcreteCreator1()
  79. concrete_creator.product.interface()
  80. concrete_creator.some_operation()
  81.  
  82.  
  83. if __name__ == "__main__":
  84. main()

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html