设计模式是解决软件设计中常见问题的可重用解决方案。Python 作为一种灵活且强大的编程语言,支持多种设计模式的实现。以下是 Python 中常见的几种设计模式及其示例:
1. 单例模式(Singleton Pattern)
确保一个类只有一个实例,并提供全局访问点。
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
# 使用
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # 输出: True
2. 工厂模式(Factory Pattern)
通过工厂类创建对象,而不是直接调用构造函数。
from abc import ABC, abstractmethod
# 抽象产品
class Animal(ABC):
@abstractmethod
def speak(self):
pass
# 具体产品
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 工厂类
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError("Unknown animal type")
# 使用
factory = AnimalFactory()
dog = factory.create_animal("dog")
print(dog.speak()) # 输出: Woof!
3. 观察者模式(Observer Pattern)
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知。
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update(self)
class Observer:
def update(self, subject):
pass
# 具体观察者
class ConcreteObserver(Observer):
def update(self, subject):
print("Subject's state has changed!")
# 使用
subject = Subject()
observer = ConcreteObserver()
subject.attach(observer)
subject.notify() # 输出: Subject's state has changed!
4. 策略模式(Strategy Pattern)
定义一系列算法,并将它们封装在独立的类中,使它们可以互相替换。
from abc import ABC, abstractmethod
# 策略接口
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
# 具体策略
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paid {amount} via Credit Card")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paid {amount} via PayPal")
# 上下文类
class PaymentContext:
def __init__(self, strategy: PaymentStrategy):
self._strategy = strategy
def execute_payment(self, amount):
self._strategy.pay(amount)
# 使用
context = PaymentContext(CreditCardPayment())
context.execute_payment(100) # 输出: Paid 100 via Credit Card
5. 装饰器模式(Decorator Pattern)
动态地为对象添加功能,而不改变其结构。
class Coffee:
def cost(self):
return 5
class MilkDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 2
class SugarDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 1
# 使用
coffee = Coffee()
coffee_with_milk = MilkDecorator(coffee)
coffee_with_milk_and_sugar = SugarDecorator(coffee_with_milk)
print(coffee_with_milk_and_sugar.cost()) # 输出: 8
6. 适配器模式(Adapter Pattern)
将一个类的接口转换成客户端期望的另一个接口。
class EuropeanSocket:
def voltage(self):
return 230
class USASocket:
def voltage(self):
return 120
class Adapter:
def __init__(self, socket):
self._socket = socket
def voltage(self):
if isinstance(self._socket, EuropeanSocket):
return self._socket.voltage() / 2
return self._socket.voltage()
# 使用
european_socket = EuropeanSocket()
adapter = Adapter(european_socket)
print(adapter.voltage()) # 输出: 115
7. 命令模式(Command Pattern)
将请求封装为对象,从而使不同的请求、队列或日志支持参数化操作。
class Command(ABC):
@abstractmethod
def execute(self):
pass
class LightOnCommand(Command):
def __init__(self, light):
self._light = light
def execute(self):
self._light.on()
class Light:
def on(self):
print("Light is on")
# 使用
light = Light()
command = LightOnCommand(light)
command.execute() # 输出: Light is on
8. 模板方法模式(Template Method Pattern)
定义一个算法的框架,允许子类在不改变结构的情况下重写某些步骤。
from abc import ABC, abstractmethod
class Game(ABC):
def play(self):
self.initialize()
self.start()
self.end()
@abstractmethod
def initialize(self):
pass
@abstractmethod
def start(self):
pass
@abstractmethod
def end(self):
pass
class Chess(Game):
def initialize(self):
print("Chess game initialized")
def start(self):
print("Chess game started")
def end(self):
print("Chess game ended")
# 使用
chess = Chess()
chess