python -【十】单例模式与工厂模式

一、单例模式

全局创建的实例只有一个,被称为单例

新建一个 StrTools.py 文件

python 复制代码
class StrTools:

    def revers(self, param):
        return param[::-1]


# 构建一个对象
str_tools = StrTools()

新建一个 test_str_tools.py 文件

python 复制代码
# 引入 StrTools 中定义的变量
from StrTools import str_tools

# 引入单例
s1 = str_tools
s2 = str_tools

print(f's1.id={id(s1)}')  # s1.id=1858205996944
print(f's2.id={id(s2)}')  # s2.id=1858205996944

"""
输出的两个对象 id 相同,表示两个对象是同一个
"""

二、工厂模式

通过工厂方法,创建对象,无需手动创建

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()

# 创建工厂实例
f = PersonFactory()
worker = f.get_person('w')
student = f.get_person('s')
teacher = f.get_person('t')
相关推荐
金銀銅鐵8 分钟前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 小时前
Agent 流程编排
后端·python·agent
copyer_xyf1 小时前
Agent RAG
后端·python·agent
copyer_xyf1 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf2 小时前
Agent 记忆管理
后端·python·agent
星云穿梭17 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵17 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python