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")
相关推荐
Norvyn_718 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
chao_78935 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥1 小时前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
都叫我大帅哥3 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`5 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿7 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python
路人蛃10 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发