定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。节省内存,节省创建对象的开销。
非单例模式 :
- class StrTools:
- pass
-
- s1 = StrTools()
- s2 = StrTools()
- print(s1)
- print(s2)
单例模式 :
- # tr_tools.py
- class StrTools:
- pass
-
- str_tool = StrTools()
- # 单例模式.py
- from str_tools import str_tool
- s1 = str_tool
- s2 = str_tool
- print(s1)
- print(s2)
定义:将对象的创建由使用原声类本身创建转换为由特定的工厂方法来创建,大量创建一个类的实例--易于维护,当发生修改,修改工厂的创建方法即可
- 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")