【Python】设计模式

设计模式分为三种类型,共23类。

  • 创建型模式:单例模式、抽象工厂模式、建造者模式、工厂模式、原型模式。
  • 结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。
  • 行为型模式:模版方法模式、命令模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、策略模式、职责链模式、访问者模式。

除了设计模式,还有六大设计原则:

  • 单一职责原则(Single Responsibility Principle)

  • 开闭原则(Open Closed Principle)

  • 里氏替换原则(Liskov Substitution Principle)

  • 迪米特法则(Law of Demeter),又叫“最少知道法则”

  • 接口隔离原则(Interface Segregation Principle)

  • 依赖倒置原则(Dependence Inversion Principle)。

单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

  • 定义:保证一个类只有一个实例,并提供一个访问它的全局访问点
  • 适用场景:当一个类只能有一个实例,而客户可以从一个众所周知的访问点访问它时。

单例的实现模式:

  1. 在一个文件中定义如上代码

    class Tools:
        pass
    
    tool = Tools()
    
  2. 在另一个文件中导入对象

    from tools import tool
    
    t1 = tool
    t2 = tool
    
    print(t1)   # 
    print(t2)   # 
    
    print(id(t1))   # 2243031289280
    print(id(t2))   # 2243031289280
    
  3. 可以看出t1和t2是同一个对象。

单例模式优点:

  • 节省内存
  • 节省创建对象的开销

工厂模式

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

# 工厂模式
class Person:
    pass

class Worker(Person):
    pass

class Student(Person):
    pass

class Teacher(Person):
    pass

class Factory:
    @classmethod    # 将该类方法定义为静态方法
    def get_person(self, p_type):
        if p_type == 'w':
            return Worker()
        elif p_type == 's':
            return Student()
        else:
            return Teacher()


worker = Factory.get_person('w')
student = Factory.get_person('s')
teacher = Factory.get_person('t')

print(worker)
print(student)
print(teacher)

你可能感兴趣的:(Python,python,设计模式,开发语言)