设计模式(3)
时间: 2024-10-18 21:57:12
(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)
二、结构型模式
1. 适配器模式(Adapter Pattern)
- 特点:将一个类的接口转换成客户期望的另一种接口。
- 适用场景:两个不兼容的接口需要一起工作时。
pythonclass Target:
def request(self):
return "普通目标"
class Adaptee:
def specific_request(self):
return "特殊请求"
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
return self.adaptee.specific_request()
adaptee = Adaptee()
adapter = Adapter(adaptee)
print(adapter.request()) # 输出: 特殊请求
2. 桥接模式(Bridge Pattern)
- 特点:将抽象部分与实现部分分离,使它们可以独立变化。
- 适用场景:需要在多个维度进行扩展时。
pythonclass Abstraction:
def __init__(self, implementor):
self.implementor = implementor
def operation(self):
return self.implementor.implementation()
class Implementor:
def implementation(self):
return "具体实现"
implementor = Implementor()
abstraction = Abstraction(implementor)
print(abstraction.operation()) # 输出: 具体实现
3. 装饰器模式(Decorator Pattern)
- 特点:动态地给一个对象添加额外的职责,适用功能的扩展。
- 适用场景:需要在运行时增加或改变对象的功能。
pythonclass Component:
def operation(self):
return "基本功能"
class Decorator(Component):
def __init__(self, component):
self.component = component
def operation(self):
return f"{self.component.operation()} + 装饰功能"
component = Component()
decorator = Decorator(component)
print(decorator.operation()) # 输出: 基本功能 + 装饰功能
4. 外观模式(Facade Pattern)
- 特点:为子系统提供一个统一的接口,让子系统更容易使用。
- 适用场景:当你需要简化对复杂子系统的调用时。
pythonclass SubsystemA:
def operation_a(self):
return "子系统A"
class SubsystemB:
def operation_b(self):
return "子系统B"
class Facade:
def __init__(self):
self.subsystem_a = SubsystemA()
self.subsystem_b = SubsystemB()
def operation(self):
return f"{self.subsystem_a.operation_a()} + {self.subsystem_b.operation_b()}"
facade = Facade()
print(facade.operation()) # 输出: 子系统A + 子系统B
5. 组合模式(Composite Pattern)
- 特点:将对象组合成树形结构以表示部分-整体层次结构。
- 适用场景:需要处理树形结构,如文件系统。
pythonclass Component:
def operation(self):
pass
class Leaf(Component):
def operation(self):
return "叶子"
class Composite(Component):
def __init__(self):
self.children = []
def add(self, component):
self.children.append(component)
def operation(self):
return "组合: " + " + ".join(child.operation() for child in self.children)
composite = Composite()
composite.add(Leaf())
print(composite.operation()) # 输出: 组合: 叶子
6. 享元模式(Flyweight Pattern)
- 特点:通过共享对象来支持大量细粒度的对象。
- 适用场景:避免创建过多相似对象时。
pythonclass Flyweight:
def __init__(self, intrinsic_state):
self.intrinsic_state = intrinsic_state
def operation(self, extrinsic_state):
return f"内部状态: {self.intrinsic_state}, 外部状态: {extrinsic_state}"
class FlyweightFactory:
def __init__(self):
self.flyweights = {}
def get_flyweight(self, state):
if state not in self.flyweights:
self.flyweights[state] = Flyweight(state)
return self.flyweights[state]
factory = FlyweightFactory()
flyweight = factory.get_flyweight("状态1")
print(flyweight.operation("外部状态")) # 输出: 内部状态: 状态1, 外部状态: 外部状态
三、行为型模式
1. 观察者模式(Observer Pattern)
- 特点:定义了一种一对多的依赖关系,使得当一个对象变化时,其依赖者会收到通知。
- 适用场景:事件驱动的系统,如 GUI 工具。
pythonclass Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def notify(self, message):
for observer in self.observers:
observer.update(message)
class Observer:
def update(self, message):
print(f"接收到消息: {message}")
subject = Subject()
observer = Observer()
subject.attach(observer)
subject.notify("状态已改变") # 输出: 接收到消息: 状态已改变
2. 策略模式(Strategy Pattern)
- 特点:定义一系列算法,将它们封装起来,可互相替换。
- 适用场景:有多种算法可以选择时。
pythonclass Strategy:
def execute(self, a, b):
pass
class ConcreteStrategyAdd(Strategy):
def execute(self, a, b):
return a + b
class ConcreteStrategySubtract(Strategy):
def execute(self, a, b):
return a - b
class Context:
def __init__(self, strategy):
self.strategy = strategy
def do_action(self, a, b):
return self.strategy.execute(a, b)
context = Context(ConcreteStrategyAdd())
print(context.do_action(5, 3)) # 输出: 8
3. 状态模式(State Pattern)
- 特点:允许一个对象在其内部状态发生改变时改变其行为。
- 适用场景:需要根据对象状态变化来控制流程。
pythonclass State:
def handle(self):
pass
class ConcreteStateA(State):
def handle(self):
return "状态 A"
class ConcreteStateB(State):
def handle(self):
return "状态 B"
class Context:
def __init__(self):
self.state = ConcreteStateA()
def set_state(self, state):
self.state = state
def request(self):
return self.state.handle()
context = Context()
print(context.request()) # 输出: 状态 A
context.set_state(ConcreteStateB())
print(context.request()) # 输出: 状态 B
4. 责任链模式(Chain of Responsibility Pattern)
- 特点:将请求的发送者与接收者解耦,使多个对象都有机会处理请求。
- 适用场景:需要将请求处理者进行解耦的场景,如事件处理。
pythonclass Handler:
def set_next(self, handler):
self.next_handler = handler
return handler
def handle(self, request):
if hasattr(self, 'next_handler'):
return self.next_handler.handle(request)
class ConcreteHandlerA(Handler):
def handle(self, request):
if request == "A":
return "处理 A"
return super().handle(request)
class ConcreteHandlerB(Handler):
def handle(self, request):
if request == "B":
return "处理 B"
return super().handle(request)
handler_a = ConcreteHandlerA()
handler_b = ConcreteHandlerB()
handler_a.set_next(handler_b)
print(handler_a.handle("A")) # 输出: 处理 A
print(handler_a.handle("B")) # 输出: 处理 B
5. 命令模式(Command Pattern)
- 特点:将请求封装为一个对象,从而使用户可以使用不同的请求。
- 适用场景:需要支持撤销操作的场合,比如在文本编辑器中的命令。
pythonclass Command:
def execute(self):
pass
class ConcreteCommand(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
return self.receiver.action()
class Receiver:
def action(self):
return "接收者的动作"
command = ConcreteCommand(Receiver())
print(command.execute()) # 输出: 接收者的动作
6. 访问者模式(Visitor Pattern)
- 特点:允许在不修改类的前提下,为对象结构中的各元素定义新操作。
- 适用场景:当需要对不同的对象元素进行不同操作时。
pythonclass Visitor:
def visit(self, element):
pass
class ConcreteVisitor(Visitor):
def visit(self, element):
return f"访问了: {element.name}"
class Element:
def __init__(self, name):
self.name = name
def accept(self, visitor):
return visitor.visit(self)
element = Element("元素1")
visitor = ConcreteVisitor()
print(element.accept(visitor)) # 输出: 访问了: 元素1
小结
以上是一些常见的设计模式及其实现示例。理解和运用设计模式可以提升代码的结构性和灵活性。在实际开发中,选择合适的设计模式并组合使用,可以有效地解决复杂的问题,降低代码维护成本。在学习设计模式的过程中,也建议多进行实践,通过项目经验加深理解。希望这些信息对你有所帮助!如果你有任何其他问题或想要深入探