什么是设计模式(Design pattern)

编程 · 2023-12-01 · 256 人浏览

设计模式

一个问题通常有n种解法,其中肯定有一种解法是最优的,这个最优的解法被人总结出来了,称之为设计模式。

设计模式有20多种,对应20多种软件开发中会遇到的问题。

单例模式

确保一个类只有一个对象。

写法:

  • 把类的构造器私有
  • 定义一个类变量记住类的一个对象
  • 定义一个类方法,返回对象

Python实现

a.py文件:

class Tools:
    pass

tool = Tools()

b.py文件:

from a import tool

t1 = tool
t2 = tool
print(t1)
print(t2)

工厂模式

当需要大量创建一个类的实例的时候,可以使用工厂模式。即,从原生的使用类的构造去创建对象的形式,迁移到,基于工厂提供的方法去创建对象的形式。

Python实现

class Person:
    pass

class Teacher(Person):
    pass

class Student(Person):
    pass

class Factory:
    def get_person(self, p_type):
        if p_type == "t":
            return Teacher()
        elif p_type == "s":
            return Student()

factory = Factory()
teacher = factory.get_person("t")
student = factory.get_person("s")
Python
Theme Jasmine by Kent Liao