python---设计模式(单例模式和工厂模式)

单例模式

复制代码
定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。节省内存,节省创建对象的开销。

非单例模式 :

python 复制代码
class StrTools:
    pass

s1 = StrTools()
s2 = StrTools()
print(s1)
print(s2)

单例模式 :

python 复制代码
# tr_tools.py
class StrTools:
    pass

str_tool = StrTools()
python 复制代码
# 单例模式.py
from str_tools import str_tool
s1 = str_tool
s2 = str_tool
print(s1)
print(s2)

工厂模式

复制代码
定义:将对象的创建由使用原声类本身创建转换为由特定的工厂方法来创建,大量创建一个类的实例--易于维护,当发生修改,修改工厂的创建方法即可
python 复制代码
class Person:
    pass


class Worker(Person):
    pass


class Student(Person):
    pass


class Teacher(Person):
    pass


class PersonFactory:
   def get_person(self,p_type):
       if p_type == 'w':
           return Worker()
       elif p_type == 's':
           return Student()
       else:
           return Teacher()


pf = PersonFactory()
worker = pf.get_person("w")
stu = pf.get_person("s")
teacher = pf.get_person("t")
相关推荐
喝凉白开都长肉的大胖子7 分钟前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib
HAPPY酷1 小时前
Python高级架构师之路——从原理到实战
java·python·算法
Thomas.Sir2 小时前
第十三章:RAG知识库开发之【GraphRAG 从基础到实战】
python·ai·rag·graphrag
一个处女座的程序猿O(∩_∩)O2 小时前
Python基础知识大全:从零开始掌握Python核心语法
开发语言·python
小陈工2 小时前
Python Web开发入门(十一):RESTful API设计原则与最佳实践——让你的API既优雅又好用
开发语言·前端·人工智能·后端·python·安全·restful
deephub3 小时前
ADK 多智能体编排:SequentialAgent、ParallelAgent 与 LoopAgent 解析
人工智能·python·大语言模型·agent
FL16238631293 小时前
基于yolov26+pyqt5的混凝土墙面缺陷检测系统python源码+pytorch模型+评估指标曲线+精美GUI界面
python·qt·yolo
cxr8283 小时前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
枫叶林FYL4 小时前
第10章 符号推理与神经符号AI
pytorch·python·深度学习
nimadan124 小时前
剧本杀app2025推荐,多类型剧本体验与社交互动优势
人工智能·python