首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python: Interpreter Pattern

python: Interpreter Pattern

作者头像
geovindu
发布2026-06-18 19:24:04
发布2026-06-18 19:24:04
1280
举报

项目结构:

代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:43
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_context.py
 
 
from dataclasses import dataclass
 
@dataclass
class JewelryContext:
    """
    珠宝上下文:存储所有珠宝属性
    """
    name: str = ""
    material: str = ""
    weight: float = 0.0
    purity: float = 0.0
    price: float = 0.0
    clarity: str = ""
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:50
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : base_expression.py
 
from abc import ABC, abstractmethod
from Interpreter.context.jewelry_context import JewelryContext
 
class BaseExpression(ABC):
    """
    职责:抽象表达式(所有规则必须实现)
    """
    @abstractmethod
    def interpret(self, context: JewelryContext) -> bool | float:
        """
        解释规则:返回判断结果 或 计算结果
        :param context:
        :return:
        """
        pass
 
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:54
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : calculate_exp.py
 
 
from Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContext
 
class GoldPriceExpression(BaseExpression):
    """
    原子规则:黄金价格计算(可扩展钻石 / 宝石)
    """
    def __init__(self, base_price: float, craft_fee: float):
        """
 
        :param base_price:
        :param craft_fee:
        """
        self.base_price = base_price
        self.craft_fee = craft_fee
 
    def interpret(self, context: JewelryContext) -> float:
        """
 
        :param context:
        :return:
        """
        total = context.weight * self.base_price + self.craft_fee
        return round(total, 2)
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:52
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : compare_exp.py
 
 
from Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContext
 
class GreaterThanExpression(BaseExpression):
    """
    原子规则:数值比较 >=
    """
    def __init__(self, field: str, threshold: float):
        """
 
        :param field:
        :param threshold:
        """
        self.field = field
        self.threshold = threshold
 
    def interpret(self, context: JewelryContext) -> bool:
        """
 
        :param context:
        :return:
        """
        value = getattr(context, self.field, 0.0)
        return value >= self.threshold
 
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:53
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : material_exp.py
 
from Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContext
 
class MaterialMatchExpression(BaseExpression):
    """
    原子规则:材质匹配
    """
    def __init__(self, material: str):
        """
 
        :param material:
        """
        self.material = material
 
    def interpret(self, context: JewelryContext) -> bool:
        """
 
        :param context:
        :return:
        """
        return context.material == self.material
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:55
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : and_exp.py
 
from Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContext
 
class AndExpression(BaseExpression):
    """
    组合规则:AND
    """
    def __init__(self, exp1: BaseExpression, exp2: BaseExpression):
        """
 
        :param exp1:
        :param exp2:
        """
        self.exp1 = exp1
        self.exp2 = exp2
 
    def interpret(self, context: JewelryContext) -> bool:
        """
 
        :param context:
        :return:
        """
        return self.exp1.interpret(context) and self.exp2.interpret(context)
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:55
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : or_exp.py
 
 
from Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContext
 
class OrExpression(BaseExpression):
    """
    组合规则:OR
    """
    def __init__(self, exp1: BaseExpression, exp2: BaseExpression):
        """
 
        :param exp1:
        :param exp2:
        """
        self.exp1 = exp1
        self.exp2 = exp2
 
    def interpret(self, context: JewelryContext) -> bool:
        """
 
        :param context:
        :return:
        """
        return self.exp1.interpret(context) or self.exp2.interpret(context)
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:56
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_rule_service.py
 
 
from Interpreter.context.jewelry_context import JewelryContext
from Interpreter.expression.base_expression import BaseExpression
 
class JewelryRuleService:
    """
    业务服务层:对外提供规则解释能力(解耦调用方)
    """
    @staticmethod
    def evaluate(expression: BaseExpression, context: JewelryContext) -> bool | float:
        """
        执行规则解释
        :param expression:
        :param context:
        :return:
        """
        return expression.interpret(context)

调用:

代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 22:01
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : InterpreterBll.py
'''

 
'''
from Interpreter.context.jewelry_context import JewelryContext
from Interpreter.expression.terminal.compare_exp import GreaterThanExpression
from Interpreter.expression.terminal.material_exp import MaterialMatchExpression
from Interpreter.expression.terminal.calculate_exp import GoldPriceExpression
from Interpreter.expression.non_terminal.and_exp import AndExpression
from Interpreter.service.jewelry_rule_service import JewelryRuleService
 
class InterpreterBll(object):
    """
 
    """
 
    def demo(self):
        """
 
        :return:
        """
        # 1. 构建珠宝上下文
        jewelry = JewelryContext(
            name="999足金戒指",
            material="黄金",
            weight=5.2,
            purity=99.9,
            clarity="VS1"
        )
 
        # 2. 规则服务
        service = JewelryRuleService()
 
        # ------------------- 规则1:计算黄金价格 -------------------
        price_exp = GoldPriceExpression(base_price=450, craft_fee=150)
        price = service.evaluate(price_exp, jewelry)
        print(f"售价:{price} 元")
 
        # ------------------- 规则2:高品质黄金 -------------------
        high_purity = GreaterThanExpression("purity", 99.9)
        is_gold = MaterialMatchExpression("黄金")
        high_quality_exp = AndExpression(high_purity, is_gold)
        result = service.evaluate(high_quality_exp, jewelry)
        print(f"是否高品质黄金:{result}")
 
        # ------------------- 规则3:高端珠宝 -------------------
        platinum = JewelryContext(material="铂金", price=6800)
        high_price = GreaterThanExpression("price", 5000)
        is_platinum = MaterialMatchExpression("铂金")
        filter_exp = AndExpression(high_price, is_platinum)
        print(f"是否高端珠宝:{service.evaluate(filter_exp, platinum)}")

输出:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-04-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档