本文将从多个方面对常用设计模式在Python中的实现进行详细阐述。
一、工厂模式
工厂模式是一种创建型设计模式,它提供了一种创建对象的方法,将对象的创建与使用分离。在Python中,可以通过使用类来实现工厂模式。
class Car:
def __init__(self, brand):
self.brand = brand
def drive(self):
print("Driving a", self.brand, "car.")
class CarFactory:
def create_car(self, brand):
return Car(brand)
factory = CarFactory()
car = factory.create_car("BMW")
car.drive()
在上面的例子中,CarFactory类充当了一个工厂,通过create_car方法来创建Car对象。这样,在使用Car对象时,我们可以直接通过工厂来创建,而不需要关心具体的实现细节。
二、单例模式
单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点。在Python中,可以通过使用模块来实现单例模式。
# singleton.py
class Singleton:
def __init__(self):
pass
instance = Singleton()
在上面的例子中,我们定义了一个Singleton类,并在模块中创建了一个实例instance。由于模块在整个程序中只会被导入一次,所以在任何地方导入singleton模块时,都将使用相同的实例。
三、观察者模式
观察者模式是一种行为型设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,其依赖对象将自动收到通知并进行相应的操作。在Python中,可以使用观察者模式实现事件驱动的程序。
class Event:
def __init__(self):
self.handlers = []
def attach(self, handler):
self.handlers.append(handler)
def detach(self, handler):
self.handlers.remove(handler)
def notify(self, *args, **kwargs):
for handler in self.handlers:
handler(*args, **kwargs)
class Button:
def __init__(self):
self.clicked = Event()
def click(self):
self.clicked.notify()
def button_clicked():
print("Button clicked!")
button = Button()
button.clicked.attach(button_clicked)
button.click()
在上面的例子中,我们定义了一个Event类来实现观察者模式,Button类充当了被观察者,button_clicked函数是一个处理事件的观察者。当按钮被点击时,会通知所有的观察者执行相应的处理函数。
四、策略模式
策略模式是一种行为型设计模式,它定义了一系列可互换的算法,并封装了每个算法的实现,使得它们可在不同的上下文中互换使用。在Python中,可以使用函数来实现策略模式。
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
class Calculator:
def __init__(self, operation):
self.operation = operation
def calculate(self, a, b):
return self.operation(a, b)
calculator = Calculator(add)
result = calculator.calculate(1, 2)
print(result)
在上面的例子中,我们定义了一些可互换的算法函数,Calculator类充当了上下文,通过传入不同的算法函数来实现不同的计算。
五、装饰器模式
装饰器模式是一种结构型设计模式,它允许将新的行为动态地添加到对象中,且不改变其原有的结构。在Python中,装饰器是一种特殊的函数,它可以用来修饰其他函数或类。
def decorator(func):
def wrapper(*args, **kwargs):
print("Before function call.")
result = func(*args, **kwargs)
print("After function call.")
return result
return wrapper
@decorator
def greet(name):
print("Hello,", name)
return "Greeting complete."
greet("Tom")
在上面的例子中,我们定义了一个装饰器函数decorator,它用于在原有的函数调用前后打印日志信息。通过在函数定义前加上@decorator语法糖,可以将greet函数修饰为带有日志功能的函数。
六、模板方法模式
模板方法模式是一种行为型设计模式,它定义了一个操作中的算法框架,将一些步骤的具体实现延迟到子类中。在Python中,可以使用抽象基类和模板方法来实现模板方法模式。
from abc import ABC, abstractmethod
class AbstractClass(ABC):
def template_method(self):
self._step1()
self._step2()
self._step3()
@abstractmethod
def _step1(self):
pass
@abstractmethod
def _step2(self):
pass
@abstractmethod
def _step3(self):
pass
class ConcreteClass(AbstractClass):
def _step1(self):
print("Step 1")
def _step2(self):
print("Step 2")
def _step3(self):
print("Step 3")
concrete = ConcreteClass()
concrete.template_method()
在上面的例子中,我们定义了一个抽象基类AbstractClass,其中template_method方法定义了一个算法框架,具体的步骤实现由子类ConcreteClass提供。
七、适配器模式
适配器模式是一种结构型设计模式,它将一个类的接口转换成客户端所期望的另一种接口。在Python中,可以使用类继承和组合来实现适配器模式。
class Adaptee:
def specific_request(self):
return "Specific request"
class Adapter:
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
return self.adaptee.specific_request()
adaptee = Adaptee()
adapter = Adapter(adaptee)
result = adapter.request()
print(result)
在上面的例子中,Adaptee类提供了一个特定的接口specific_request,Adapter类通过调用Adaptee类的接口来实现request方法,将Adaptee接口转换成适应客户端的接口。
八、迭代器模式
迭代器模式是一种行为型设计模式,它提供一种方法顺序访问一个聚合对象中的各个元素,而不需要暴露其内部表示。在Python中,可以使用迭代器对象和可迭代对象来实现迭代器模式。
class Iterator:
def __iter__(self):
return self
def __next__(self):
raise StopIteration()
class Iterable:
def __iter__(self):
return Iterator()
iterable = Iterable()
for item in iterable:
print(item)
在上面的例子中,Iterator类实现了__iter__和__next__方法,使得其可以被迭代。Iterable类实现了__iter__方法,返回一个迭代器对象,在迭代时输出每个元素。
九、命令模式
命令模式是一种行为型设计模式,它将一个请求封装成一个对象,使得可以用不同的请求对客户端进行参数化。在Python中,可以使用命令类和命令接收者来实现命令模式。
class Command:
def execute(self):
pass
class ConcreteCommand(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action()
class Receiver:
def action(self):
print("Action executed")
receiver = Receiver()
command = ConcreteCommand(receiver)
command.execute()
在上面的例子中,Command类定义了一个execute方法,ConcreteCommand类继承自Command类并实现了execute方法,Receiver类定义了一个action方法。通过将命令和命令接收者解耦,客户端可以用不同的命令来参数化Receiver对象,实现不同的功能。
十、组合模式
组合模式是一种结构型设计模式,它以一种树形结构组织对象,使得客户端可以以一致的方式处理单个对象和组合对象。在Python中,可以使用递归和多态来实现组合模式。
class Component:
def operation(self):
pass
class Leaf(Component):
def operation(self):
print("Leaf operation")
class Composite(Component):
def __init__(self):
self.components = []
def add(self, component):
self.components.append(component)
def remove(self, component):
self.components.remove(component)
def operation(self):
for component in self.components:
component.operation()
composite = Composite()
composite.add(Leaf())
composite.operation()
在上面的例子中,Component类定义了一个operation方法,Leaf类和Composite类都继承自Component类并实现了operation方法。通过将叶子和组合对象归一化处理,客户端可以以相同的方式处理单个对象和组合对象。