Python 工厂方法模式讲解和代码示例

简介: Python 工厂方法模式讲解和代码示例

使用示例工厂方法模式在 Python 代码中得到了广泛使用 当你需要在代码中提供高层次的灵活性时 该模式会非常实用

识别方法工厂方法可通过构建方法来识别 它会创建具体类的对象 但以抽象类型或接口的形式返回这些对象

01概念示例

本例说明了工厂方法设计模式的结构并重点回答了下面的问题

  • 它由哪些类组成
  • 这些类扮演了哪些角色
  • 模式中的各个元素会以何种方式相互关联


概念示例

from __future__ import annotations
from abc import ABC, abstractmethod
class Creator(ABC):
    """
    The Creator class declares the factory method that is supposed to return an
    object of a Product class. The Creator's subclasses usually provide the
    implementation of this method.
    """
    @abstractmethod
    def factory_method(self):
        """
        Note that the Creator may also provide some default implementation of
        the factory method.
        """
        pass
    def some_operation(self) -> str:
        """
        Also note that, despite its name, the Creator's primary responsibility
        is not creating products. Usually, it contains some core business logic
        that relies on Product objects, returned by the factory method.
        Subclasses can indirectly change that business logic by overriding the
        factory method and returning a different type of product from it.
        """
        #Call the factory method to create a Product object.
        product = self.factory_method()
        #Now, use the product.
        result = f"Creator: The same creator's code has just worked with {product.operation()}"
        return result
"""
Concrete Creators override the factory method in order to change the resulting
product's type.
"""
class ConcreteCreator1(Creator):
    """
    Note that the signature of the method still uses the abstract product type,
    even though the concrete product is actually returned from the method. This
    way the Creator can stay independent of concrete product classes.
    """
    def factory_method(self) -> Product:
        return ConcreteProduct1()
class ConcreteCreator2(Creator):
    def factory_method(self) -> Product:
        return ConcreteProduct2()
class Product(ABC):
    """
    The Product interface declares the operations that all concrete products
    must implement.
    """
    @abstractmethod
    def operation(self) -> str:
        pass
"""
Concrete Products provide various implementations of the Product interface.
"""
class ConcreteProduct1(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct1}"
class ConcreteProduct2(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct2}"
def client_code(creator: Creator) -> None:
    """
    The client code works with an instance of a concrete creator, albeit through
    its base interface. As long as the client keeps working with the creator via
    the base interface, you can pass it any creator's subclass.
    """
    print(f"Client: I'm not aware of the creator's class, but it still works.\n"
          f"{creator.some_operation()}", end="")
if __name__ == "__main__":
    print("App: Launched with the ConcreteCreator1.")
    client_code(ConcreteCreator1())
    print("\n")
    print("App: Launched with the ConcreteCreator2.")
    client_code(ConcreteCreator2())


 执行结果

App: Launched with the ConcreteCreator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct1}
App: Launched with the ConcreteCreator2.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct2}


相关文章
|
4天前
|
机器学习/深度学习 数据采集 算法
数据稀缺条件下的时间序列微分:符号回归(Symbolic Regression)方法介绍与Python示例
有多种方法可以处理时间序列数据中的噪声。本文将介绍一种在我们的研究项目中表现良好的方法,特别适用于时间序列概况中数据点较少的情况。
16 1
数据稀缺条件下的时间序列微分:符号回归(Symbolic Regression)方法介绍与Python示例
|
3天前
|
设计模式 开发框架 缓存
探索Python中的装饰器:简化代码,增强功能
【9月更文挑战第16天】在Python的世界里,装饰器宛如一位巧手魔术师,轻轻一挥魔杖,便能让我们的函数和类焕发新生。本文将带你领略装饰器的魔力,从基础概念到实战应用,一步步解锁装饰器的强大潜能。让我们一起踏上这段奇妙的旅程,探索如何用装饰器简化代码,增强功能。
|
5天前
|
XML 数据格式 Python
Python技巧:将HTML实体代码转换为文本的方法
在选择方法时,考虑到实际的应用场景和需求是很重要的。通常,使用标准库的 `html`模块就足以满足大多数基本需求。对于复杂的HTML文档处理,则可能需要 `BeautifulSoup`。而在特殊场合,或者为了最大限度的控制和定制化,可以考虑正则表达式。
21 12
|
5天前
|
测试技术 开发者 Python
探索Python中的装饰器:简化代码,增强功能
【9月更文挑战第14天】在编程世界中,我们总是寻找使代码更简洁、更强大的方法。Python的装饰器正是这样一项工具,它允许我们在不修改原有函数代码的情况下,增加额外的功能。本文将通过实际示例,引导你理解装饰器的基本概念,展示如何创建和应用它们,以及如何利用装饰器简化日常编程任务。无论你是初学者还是有经验的开发者,这篇文章都将为你提供新的视角和技巧,让你的代码更加高效和优雅。
21 12
|
3天前
|
测试技术 Python
Python中的装饰器:简化代码的魔法
【9月更文挑战第16天】在Python编程的世界里,装饰器就像是一把瑞士军刀,它们为函数和类赋予了额外的超能力。本文将带你探索装饰器的秘密,了解如何利用这一工具来简化代码、增强可读性并提升效率。从基础概念到实际案例,我们将一步步揭示装饰器的神秘面纱,让你的代码更加优雅和强大。
|
3天前
|
设计模式 缓存 开发者
探索Python中的装饰器:提升代码复用性的利器
本文深入探讨了Python中强大的装饰器功能,揭示了其如何通过元编程和闭包等技术手段,优雅地实现代码的复用与扩展。从基本概念到高级应用,我们将一步步揭开装饰器背后的奥秘,并通过实例展示其在实际项目开发中的巨大价值。无论是想要简化函数调用流程、增强函数功能,还是实现AOP(面向切面编程),掌握装饰器都是每位Python开发者必备的技能。
|
4天前
|
缓存 开发者 Python
探索Python中的装饰器:简化代码,增强功能
【9月更文挑战第15天】本文将深入探讨Python中一个强大但常被误解的特性——装饰器。我们将从基础概念出发,逐步揭示装饰器如何简化代码结构,增加函数功能而无需修改其核心逻辑。通过具体示例,你将学会如何创建自定义装饰器,以及如何利用它们来管理权限、记录日志等。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇提高代码效率和可维护性的新窗口。
|
2天前
|
缓存 监控 测试技术
探索Python中的装饰器:提升代码的灵活性和可维护性
本文深入探讨Python装饰器的概念、用法及优势。通过实例讲解如何利用装饰器增强函数功能、日志记录及性能测试,旨在帮助读者掌握这一强大的工具,提升编程效率与代码质量。
|
3天前
|
缓存 开发者 Python
探索Python中的装饰器:提升代码复用性与可读性
本文旨在深入探讨Python装饰器的概念、实现及其应用。通过实例分析,本文展示了如何利用装饰器提高代码的模块化和重用性,从而优化开发流程。我们将从装饰器的基本定义入手,逐步解析其工作机制,并通过案例展示如何在实际项目中有效利用装饰器。
6 0
|
3天前
|
数据处理 开发者 Python
探索Python中的列表推导式在Python编程中,列表推导式是一种简洁而高效的方法,用于从现有的列表创建新列表。本文将深入探讨列表推导式的用法、优势以及一些实际应用示例。
列表推导式是Python提供的一种强大工具,它允许开发者以更简洁的语法快速生成列表。通过结合循环和条件语句,列表推导式能够简化代码结构,提高开发效率。本文详细介绍了列表推导式的基本用法,并通过实例展示了其在数据处理、转换和过滤中的广泛应用。
9 0