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")
相关推荐
hboot9 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
Larcher13 小时前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
用户83562907805114 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户83562907805116 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠21 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz31021 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780512 天前
使用 Python 操作 Word 内容控件
后端·python
咖啡八杯2 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式