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')
相关推荐
Flittly17 分钟前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风7 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风7 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风2 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python