面向对象编程(OOP)是 Python 中一种强大的编程范式。通过使用面向对象设计模式,我们可以创建出更加模块化、可重用和易于维护的代码。以下是一些常见的 Python 面向对象设计模式:

单例模式(Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

class Singleton:
    _instance = None

    @staticmethod
    def getInstance():
        if Singleton._instance == None:
            Singleton._instance = Singleton()
        return Singleton._instance

工厂模式(Factory)

工厂模式用于创建对象,而不直接指定对象的具体类。

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class AnimalFactory:
    def get_animal(self, animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()
        else:
            return None

装饰器模式(Decorator)

装饰器模式允许你动态地给一个对象添加一些额外的职责。

def make_blink(func):
    def wrapper():
        return "<blink>" + func() + "</blink>"
    return wrapper

@make_blink
def hello():
    return "Hello, World!"

print(hello())

观察者模式(Observer)

观察者模式定义了对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

class Subject:
    def __init__(self):
        self._observers = []

    def register(self, observer):
        self._observers.append(observer)

    def notify(self):
        for observer in self._observers:
            observer.update()

class Observer:
    def update(self):
        pass

class ConcreteObserver(Observer):
    def update(self):
        print("Observer received notification.")

更多资源

如果你对 Python 面向对象设计模式感兴趣,可以阅读以下文章:

Python 面向对象设计模式