python: Template Method Pattern

用珠宝制作来类比再合适不过:

  • 所有珠宝(戒指、项链、手镯)的制作都有固定通用流程(算法骨架):选材 → 塑形 → 打磨 → 镶嵌 → 质检 → 成品
  • 其中,选材、打磨、质检 是通用步骤(所有珠宝都差不多)
  • 而 塑形、镶嵌 是可变步骤(戒指要塑成环形,项链要塑成链状;戒指镶嵌单颗主石,项链镶嵌多颗碎钻)
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Template Method Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/22 10:20
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelryMaker.py
# explain   : 学习
 
from abc import ABC, abstractmethod
 
 
class JewelryMaker(ABC):
    """
    抽象基类:定义珠宝制作的模板方法(算法骨架)
    """
 
    def make_jewelry(self):
        """
        模板方法:定义珠宝制作的整体流程(不允许子类重写,Python中用命名约定_开头或注释提醒)
        """
 
        self.select_material()  # 步骤1:选材(通用)
        self.shape()            # 步骤2:塑形(可变,子类实现)
        self.polish()           # 步骤3:打磨(通用)
        self.inlay()            # 步骤4:镶嵌(可变,子类实现)
        self.quality_check()    # 步骤5:质检(通用)
        print(f"【成品】{self.get_jewelry_type()}制作完成!\n")
 
 
    def select_material(self):
        """
        通用方法:所有珠宝都用相同的选材逻辑
        """
        print("1. 选材:选用925银+天然锆石")
 
 
    def polish(self):
        """
        通用方法:所有珠宝都用相同的打磨逻辑
        """
        print("3. 打磨:精细抛光至镜面效果")
 
 
    def quality_check(self):
        """
        通用方法:所有珠宝都用相同的质检逻辑
        """
        print("5. 质检:检查表面光滑度、镶嵌牢固度")
 
 
    @abstractmethod
    def shape(self):
        """
        抽象方法:塑形(子类必须实现)
        """
        pass
 
 
    @abstractmethod
    def inlay(self):
        """
        抽象方法:镶嵌(子类必须实现)
        """
        pass
 
 
    @abstractmethod
    def get_jewelry_type(self):
        """
        辅助方法:获取珠宝类型(子类实现)
        """
        pass
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Template Method Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/22 10:23
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : RingMaker.py
# explain   : 学习
 
from TemplateMethodPattern.JewelryMaker import JewelryMaker
 
 
class RingMaker(JewelryMaker):
    """
    子类1:戒指制作(实现可变步骤)
    """
    def select_material(self):
        """
        重写 选材
        """
        print("1. 选材:将k999黄金锻造成环形,内径调整为28mm")
 
    def shape(self):
        """
        塑形
        """
        print("2. 塑形:将黄金料锻造成环形,内径调整为28mm")
 
    def inlay(self):
        """
        镶嵌
        """
        print("4. 镶嵌:在戒指中心镶嵌1颗5mm圆形锆石")
 
    def get_jewelry_type(self):
        """
 
        """
        return "戒指"
 
 
 
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Template Method Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/22 10:30
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : NecklaceMaker.py
# explain   : 学习
 
from TemplateMethodPattern.JewelryMaker import JewelryMaker
 
 
class NecklaceMaker(JewelryMaker):
    """
    子类2:项链制作(实现可变步骤)
    """
    def shape(self):
        """
        塑形
        """
        print("2. 塑形:将银料拉成细链,编织成十字链样式,长度45cm")
 
    def inlay(self):
        """
        镶嵌
        """
        print("4. 镶嵌:在项链吊坠处镶嵌3颗2mm碎钻,链条间隔镶嵌小锆石")
 
    def get_jewelry_type(self):
        """
        项链
        """
        return "项链"
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/22 10:33
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : TemplateMethodBll.py
# explain   : 学习
from TemplateMethodPattern.RingMaker import RingMaker
from TemplateMethodPattern.NecklaceMaker import NecklaceMaker
 
 
class TemplateMethodBll(object):
    """
 
    """
    def demo(self):
        """
 
        """
        # 制作戒指
        ring_maker = RingMaker()
        print("=== 开始制作戒指 ===")
        ring_maker.make_jewelry()
 
        # 制作项链
        necklace_maker = NecklaceMaker()
        print("=== 开始制作项链 ===")
        necklace_maker.make_jewelry()

调用:

python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 20:58
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : main.py
# explain   : 学习
from bll.MementoBll import MementoBll
from bll.CommandBll import CommandBll
from bll.StateBll import StateBll
from bll.TemplateMethodBll import TemplateMethodBll
 
if __name__ == '__main__':
 
    #实现备忘录模式(Memento Pattern)
    #mementobll= MementoBll()
    #mementobll.demo()
    #命令模式(Command Pattern)
    #commandBll= CommandBll()
    #commandBll.demo()
    # 状态模式 State Pattern
    #stateBll =StateBll()
    #stateBll.demo()
    # 模板方法模式 Template Method Pattern
    templateMethodBll= TemplateMethodBll()
    templateMethodBll.demo()
 
    print('PyCharm')

输出:

相关推荐
在世修行4 小时前
智学文枢:数据备份与恢复
python·数据安全·备份恢复·zipfile
ONEYAC唯样4 小时前
TE:不只看产品,更要看价值:下一代高压连接方案如何选择?
python·django
高洁014 小时前
具身智能感知系统底层原理
人工智能·python·深度学习·机器学习·transformer
我就是不信4 小时前
Java8 lambda 表达式 forEach 如何提前终止?
开发语言·windows·python
Cx330❀4 小时前
深入浅出 Qt 绘图机制:从 QPainter 到四大图像类解析
开发语言·qt·ui·性能优化·图形渲染
全栈弄潮儿4 小时前
Python实战第9期:文件操作
后端·python·编程语言
小星星_ios5 小时前
从 3Blue1Brown 到 NumPy:手写一个神经网络训练 MNIST
人工智能·python·神经网络
信可维5 小时前
AI 读 Word 表格总读错?先查合并单元格和表头这 3 处
开发语言·人工智能·c#·word·软件工程
Maxwin5 小时前
Manim 竖屏画布选 9×16 还是 4.5×8?从 font_size 和每单位像素数说起
python·ffmpeg
昭昭日月明5 小时前
使用 Ragas 量化 RAG
python·langchain·ai编程