Python设计模式实战:深入理解23种经典设计模式
设计模式是一种通用、可重用的解决方案,用来解决常见设计问题,帮助程序员更加有效地设计软件。Python是一种强大的编程语言,被广泛应用于Web开发、数据分析、人工智能等领域。在Python中应用设计模式,可以提高代码的可读性、可维护性和可扩展性。
本文将介绍23种经典设计模式,并用Python实现各种设计模式的示例代码。读者可以通过这些示例代码,深入理解每种设计模式的实现原理和应用场景。
一、创建型设计模式
1. 简单工厂模式
简单工厂模式是一种创建型设计模式,它隐藏了对象的创建逻辑,并提供了一个简单的接口,来实现对象的创建。在Python中,可以通过定义一个工厂函数,来创建对象。
示例代码:
```python
class Product:
def display(self):
pass
class ConcreteProduct1(Product):
def display(self):
print("This is ConcreteProduct1")
class ConcreteProduct2(Product):
def display(self):
print("This is ConcreteProduct2")
def create_product(product_type):
if product_type == "Product1":
return ConcreteProduct1()
elif product_type == "Product2":
return ConcreteProduct2()
else:
raise ValueError("Invalid product type")
product1 = create_product("Product1")
product1.display() # Output: "This is ConcreteProduct1"
product2 = create_product("Product2")
product2.display() # Output: "This is ConcreteProduct2"
```
2. 工厂方法模式
工厂方法模式是一种创建型设计模式,它定义了一个工厂接口和多个工厂实现类,每个工厂实现类用于创建一种产品对象。在Python中,可以用抽象基类来定义工厂接口,具体子类实现工厂接口。
示例代码:
```python
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def display(self):
pass
class ConcreteProduct1(Product):
def display(self):
print("This is ConcreteProduct1")
class ConcreteProduct2(Product):
def display(self):
print("This is ConcreteProduct2")
class Creator(ABC):
@abstractmethod
def create_product(self):
pass
class ConcreteCreator1(Creator):
def create_product(self):
return ConcreteProduct1()
class ConcreteCreator2(Creator):
def create_product(self):
return ConcreteProduct2()
creator1 = ConcreteCreator1()
product1 = creator1.create_product()
product1.display() # Output: "This is ConcreteProduct1"
creator2 = ConcreteCreator2()
product2 = creator2.create_product()
product2.display() # Output: "This is ConcreteProduct2"
```
3. 抽象工厂模式
抽象工厂模式是一种创建型设计模式,它提供了一种方式,以便于创建一系列相关或相互依赖的对象,而无需指定它们的具体类。在Python中,抽象工厂模式可以用抽象基类来定义抽象工厂接口,具体子类实现抽象工厂接口。
示例代码:
```python
from abc import ABC, abstractmethod
class AbstractFactory(ABC):
@abstractmethod
def create_productA(self):
pass
@abstractmethod
def create_productB(self):
pass
class ConcreteFactory1(AbstractFactory):
def create_productA(self):
return ConcreteProductA1()
def create_productB(self):
return ConcreteProductB1()
class ConcreteFactory2(AbstractFactory):
def create_productA(self):
return ConcreteProductA2()
def create_productB(self):
return ConcreteProductB2()
class AbstractProductA(ABC):
pass
class ConcreteProductA1(AbstractProductA):
pass
class ConcreteProductA2(AbstractProductA):
pass
class AbstractProductB(ABC):
@abstractmethod
def interact(self, productA):
pass
class ConcreteProductB1(AbstractProductB):
def interact(self, productA):
print(f"{self.__class__.__name__} interacts with {productA.__class__.__name__}")
class ConcreteProductB2(AbstractProductB):
def interact(self, productA):
print(f"{self.__class__.__name__} interacts with {productA.__class__.__name__}")
factory1 = ConcreteFactory1()
productA1 = factory1.create_productA()
productB1 = factory1.create_productB()
productB1.interact(productA1) # Output: "ConcreteProductB1 interacts with ConcreteProductA1"
factory2 = ConcreteFactory2()
productA2 = factory2.create_productA()
productB2 = factory2.create_productB()
productB2.interact(productA2) # Output: "ConcreteProductB2 interacts with ConcreteProductA2"
```
4. 单例模式
单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供了全局访问点。在Python中,单例模式可以用类变量或元类实现。
示例代码:
```python
class Singleton:
instance = None
def __new__(cls):
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # Output: True
```
二、结构型设计模式
5. 适配器模式
适配器模式是一种结构型设计模式,它允许将已有的接口转化成客户端所期望的接口。在Python中,适配器模式可以用类继承或对象组合实现。
示例代码:
```python
class Target:
def request(self):
pass
class Adaptee:
def specific_request(self):
print("This is specific request")
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
self.adaptee.specific_request()
adaptee = Adaptee()
adapter = Adapter(adaptee)
adapter.request() # Output: "This is specific request"
```
6. 桥接模式
桥接模式是一种结构型设计模式,它将抽象和实现解耦,使得它们可以独立地变化。在Python中,桥接模式可以用类继承或对象组合实现。
示例代码:
```python
from abc import ABC, abstractmethod
class Implementor(ABC):
@abstractmethod
def operation_impl(self):
pass
class ConcreteImplementorA(Implementor):
def operation_impl(self):
print("This is operation_impl of ConcreteImplementorA")
class ConcreteImplementorB(Implementor):
def operation_impl(self):
print("This is operation_impl of ConcreteImplementorB")
class Abstraction:
def __init__(self, implementor):
self.implementor = implementor
def operation(self):
pass
class RefinedAbstraction(Abstraction):
def operation(self):
self.implementor.operation_impl()
implementorA = ConcreteImplementorA()
abstraction1 = RefinedAbstraction(implementorA)
abstraction1.operation() # Output: "This is operation_impl of ConcreteImplementorA"
implementorB = ConcreteImplementorB()
abstraction2 = RefinedAbstraction(implementorB)
abstraction2.operation() # Output: "This is operation_impl of ConcreteImplementorB"
```
7. 组合模式
组合模式是一种结构型设计模式,它允许将对象组成树形结构,以表示部分-整体的层次结构。在Python中,组合模式可以用类继承或对象组合实现。
示例代码:
```python
from abc import ABC, abstractmethod
class Component(ABC):
@abstractmethod
def operation(self):
pass
class Leaf(Component):
def operation(self):
print("This is operation of Leaf")
class Composite(Component):
def __init__(self):
self.children = []
def add(self, component):
self.children.append(component)
def remove(self, component):
self.children.remove(component)
def operation(self):
for child in self.children:
child.operation()
leaf1 = Leaf()
leaf2 = Leaf()
composite1 = Composite()
composite1.add(leaf1)
composite1.add(leaf2)
composite2 = Composite()
composite2.add(composite1)
composite1.operation() # Output: "This is operation of Leaf\nThis is operation of Leaf"
composite2.operation() # Output: "This is operation of Leaf\nThis is operation of Leaf"
```
8. 装饰器模式
装饰器模式是一种结构型设计模式,它动态地将责任附加到对象上,扩展对象的功能。在Python中,装饰器模式可以用函数装饰器或类装饰器实现。
示例代码:
```python
def decorator(func):
def wrapper(*args, **kwargs):
print("This is before function")
result = func(*args, **kwargs)
print("This is after function")
return result
return wrapper
@decorator
def function():
print("This is function")
function() # Output: "This is before function\nThis is function\nThis is after function"
```
9. 外观模式
外观模式是一种结构型设计模式,它为子系统提供了一个简单、一致的接口,隐藏了子系统的复杂性。在Python中,外观模式可以用类实现。
示例代码:
```python
class Subsystem1:
def operation1(self):
print("This is operation1 of Subsystem1")
class Subsystem2:
def operation2(self):
print("This is operation2 of Subsystem2")
class Facade:
def __init__(self):
self.subsystem1 = Subsystem1()
self.subsystem2 = Subsystem2()
def operation(self):
self.subsystem1.operation1()
self.subsystem2.operation2()
facade = Facade()
facade.operation() # Output: "This is operation1 of Subsystem1\nThis is operation2 of Subsystem2"
```
10. 享元模式
享元模式是一种结构型设计模式,它通过共享来减少对象的数量,从而减少内存占用和提高性能。在Python中,享元模式可以用类变量或元类实现。
示例代码:
```python
class Flyweight:
shared_state = {}
def __init__(self, unshared_state):
self.__dict__ = self.shared_state
self.unshared_state = unshared_state
def operation(self):
print(f"This is operation with unshared state {self.unshared_state}")
flyweight1 = Flyweight("state1")
flyweight2 = Flyweight("state2")
flyweight1.operation() # Output: "This is operation with unshared state state1"
flyweight2.operation() # Output: "This is operation with unshared state state2"
print(flyweight1 is flyweight2) # Output: True
```
三、行为型设计模式
11. 责任链模式
责任链模式是一种行为型设计模式,它将请求的发送者和接收者解耦,使得多个对象都有机会处理请求。在Python中,责任链模式可以用对象组合实现。
示例代码:
```python
from abc import ABC, abstractmethod
class Handler(ABC):
def __init__(self, successor=None):
self.successor = successor
@abstractmethod
def handle_request(self, request):
pass
class ConcreteHandler1(Handler):
def handle_request(self, request):
if request == "request1":
print("This is request1 handled by ConcreteHandler1")
elif self.successor is not None:
self.successor.handle_request(request)
class ConcreteHandler2(Handler):
def handle_request(self, request):
if request == "request2":
print("This is request2 handled by ConcreteHandler2")
elif self.successor is not None:
self.successor.handle_request(request)
handler1 = ConcreteHandler1()
handler2 = ConcreteHandler2(handler1)
handler2.handle_request("request1") # Output: "This is request1 handled by ConcreteHandler1"
handler2.handle_request("request2") # Output: "This is request2 handled by ConcreteHandler2"
handler2.handle_request("request3") # Output: nothing
```
12. 命令模式
命令模式是一种行为型设计模式,它将请求封装成对象,以便于记录请求日志、撤销操作、重做操作等。在Python中,命令模式可以用类实现。
示例代码:
```python
from abc import ABC, abstractmethod
class Command(ABC):
@abstractmethod
def execute(self):
pass
class Invoker:
def __init__(self):
self.command_history = []
def store_command(self, command):
self.command_history.append(command)
def run_command(self):
if len(self.command_history) > 0:
self.command_history.pop().execute()
class Receiver:
def action(self):
print("This is action of Receiver")
class ConcreteCommand(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action()
receiver = Receiver()
command = ConcreteCommand(receiver)
invoker = Invoker()
invoker.store_command(command)
invoker.run_command() # Output: "This is action of Receiver"
```
13. 解释器模式
解释器模式是一种行为型设计模式,它定义了一种语言文法,并用解释器来解释语言中的句子。在Python中,解释器模式可以用类继承实现。
示例代码:
```python
from abc import ABC, abstractmethod
class AbstractExpression(ABC):
@abstractmethod
def interpret(self, context):
pass
class TerminalExpression(AbstractExpression):
def interpret(self, context):
return context.count(self) > 0
class NonterminalExpression(AbstractExpression):
def __init__(self, expression):
self.expression = expression
def interpret(self, context):
return self.expression.interpret(context)
context = "Hello, world!"
expression1 = TerminalExpression("Hello")
expression2 = TerminalExpression("world")
expression3 = NonterminalExpression(expression1)
expression4 = NonterminalExpression(expression2)
print(expression3.interpret(context) and expression4.interpret(context)) # Output: True
```
14. 迭代器模式
迭代器模式是一种行为型设计模式,它提供了一种方法,以便于顺序地访问一个聚合对象中的元素,而无需暴