Python使用策略模式实现绘图功能

策略模式(Strategy Pattern):允许定义一系列算法,将它们封装起来,使得它们可以互换。

实现绘制不同类型的图表(如折线图、柱状图和饼图)功能。

下面是一个示例,展示如何传入横坐标和纵坐标内容,然后绘制不同类型的图表。

python 复制代码
import matplotlib.pylab as plt
from abc import ABC, abstractmethod

class PlotStrategy(ABC):
    # 抽象类:强制子类实现此方法
    @abstractmethod
    def plot(self, x_data, y_data, desc):
        pass

class LinePlotStrategy(PlotStrategy):
    def plot(self, x_data, y_data, desc):
        print('折线图')
        plt.plot(x_data,y_data,marker=0)
        plt.title(desc[0])
        plt.xlabel(desc[1])
        plt.ylabel(desc[2])
        plt.show()

class BarPlotStrategy(PlotStrategy):
    def plot(self, x_data, y_data, desc):
        print('柱状图')
        plt.bar(x_data, y_data)
        plt.title(desc[0])
        plt.xlabel(desc[1])
        plt.ylabel(desc[2])
        plt.show()

class PiePlotStrategy(PlotStrategy):
    def plot(self, x_data, y_data, desc):
        print('饼图')
        labels = x_data
        sizes = y_data
        plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
        plt.axis('equal') # 正圆形
        plt.title(desc[0])
        plt.show()


# Context类持有PlotStrategy的引用。可以通过set_strategy方法动态地更改策略
class Context:
    def __int__(self, strategy: PlotStrategy):
        # _ 开头的变量,表示这是一个受保护的变量
        # 该变量只在类内部及其子类中使用,而不应在类外部直接访问
        self._strategy = strategy

    def set_strategy(self,strategy: PlotStrategy):
        self._strategy = strategy

    def execute_strategy(self, x_data, y_data, desc):
        self._strategy.plot(x_data, y_data, desc)


x = ['A','B','C']
y = [2,3,6]
desc = ['title','x','y']

# line = LinePlotStrategy().plot(x, y, desc)
# bar = BarPlotStrategy().plot(x,  y, desc)
# pie = PiePlotStrategy().plot(x,  y, desc)

context = Context()

context.set_strategy(LinePlotStrategy())
context.execute_strategy(x,  y, desc)

context.set_strategy(BarPlotStrategy())
context.execute_strategy(x,  y, desc)

context.set_strategy(PiePlotStrategy())
context.execute_strategy(x,  y, desc)

折线图

柱状图

饼图

相关推荐
牧瀬クリスだ20 分钟前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
博风4 小时前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
电子IT笔记6 小时前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
智慧城市203010 小时前
关键供应商连续交付不合格批次,说明质量风险可能持续存在。企业需要建立“批次隔离、加严检验、驻厂遏制、复检放行、供应商升级”的处置闭环,同时统筹保供。
数据分析·策略模式·战略咨询·流程管理
博风1 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶1 天前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
happy_baymax1 天前
Dell G3 3590 黑苹果实战:OpenCore 1.0.8 + NullMoth 驱动让 GTX 1660 跑起 Metal
策略模式
遇码1 天前
macOS 触摸板捏合在 GPUI 里无响应:vendor 打补丁,把手势合成为 cmd+滚轮事件
rust·图形渲染·策略模式·桌面应用·gpui
geovindu1 天前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
拆房老料1 天前
【第四部分:Agentic 智能体设计模式】15.为什么 Agent 也需要设计模式
人工智能·设计模式·ai·ai-native