📜  python中的设计模式(1)

📅  最后修改于: 2023-12-03 15:04:37.293000             🧑  作者: Mango

Python中的设计模式

设计模式是程序开发过程中经过多年实践总结出的一系列通用的解决问题的方法或思路。在Python中,我们可以使用这些设计模式来提高程序的可读性、可维护性和可扩展性。下面介绍一些常见的设计模式。

1. 单例模式

单例模式是一种常见的创建型设计模式。它保证一个类只有一个实例,并提供全局访问点。在Python中,可以通过元类的方式来实现单例模式。

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)

        return cls._instances[cls]

class MyClass(metaclass=Singleton):
    pass

obj1 = MyClass()
obj2 = MyClass()
print(obj1 is obj2)  # True

上述代码中,通过定义元类Singleton并重写__call__()方法,可以确保一个类只有一个实例。使用时,只需要将该元类作为参数传递给被单例化的类即可。

2. 工厂模式

工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。与直接实例化对象不同,工厂模式使用工厂方法来创建对象。

class Dog:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Woof!"

    def __str__(self):
        return f"I am {self._name}, a Dog"

class Cat:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Meow!"

    def __str__(self):
        return f"I am {self._name}, a Cat"

class AnimalFactory:
    def get_animal(self, animal_type, name):
        if animal_type == "dog":
            return Dog(name)
        elif animal_type == "cat":
            return Cat(name)
        else:
            raise ValueError(f"{animal_type} is not a valid animal type")

factory = AnimalFactory()
dog = factory.get_animal("dog", "Rex")
cat = factory.get_animal("cat", "Missy")
print(dog)
print(cat)

上述代码中,AnimalFactory是一个工厂类,它使用get_animal()方法来创建不同类型的动物。使用时,只需要调用工厂类的get_animal()方法,并传递相关的参数,即可创建不同类型的对象。

3. 观察者模式

观察者模式是一种行为型设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都得到通知并自动更新状态。

class Observer:
    def update(self, temperature):
        pass

class Subject:
    def __init__(self):
        self._observers = set()

    def attach(self, observer):
        if not isinstance(observer, Observer):
            raise TypeError()
        self._observers.add(observer)

    def detach(self, observer):
        self._observers.remove(observer)

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

class TemperatureMonitor(Subject):
    def set_temperature(self, temperature):
        self.notify(temperature)

class EmailNotifier(Observer):
    def update(self, temperature):
        if temperature > 100:
            print("Sending email notification")

class Logger(Observer):
    def update(self, temperature):
        print(f"Temperature updated to {temperature}")

monitor = TemperatureMonitor()
email_notifier = EmailNotifier()
logger = Logger()
monitor.attach(email_notifier)
monitor.attach(logger)
monitor.set_temperature(99)
monitor.set_temperature(101)

上述代码中,Subject是一个主题类,它维护了所有观察者,并提供了增、删、通知观察者的方法。Observer是一个观察者接口,它定义了一个update()方法,当主题发生改变时,该方法会被调用。TemperatureMonitor是一个具体的主题类,它提供了一个set_temperature()方法来更新温度,并在更新时通知所有观察者。EmailNotifier和Logger都是具体的观察者类,它们实现了Observer接口,并在update()方法中做出相应的响应。