在本篇博文中,我们将逐个深入解析常见的设计模式,包括它们的目的、结构和具体示例,帮助你更好地理解和应用这些模式。
一、创建型模式
1. 单例模式(Singleton)
目的:确保一个类只有一个实例,并提供全局访问。
示例:
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance singleton1 = Singleton()
singleton2 = Singleton() print(singleton1 is singleton2) # Output: True
2. 工厂方法模式(Factory Method)
目的:定义一个创建对象的接口,使子类决定实例化哪一个类。
示例:
class Product: def operation(self): pass class ConcreteProductA(Product): def operation(self): return "Result of ConcreteProductA" class ConcreteProductB(Product): def operation(self): return "Result of ConcreteProductB" class Creator: def factory_method(self): raise NotImplementedError class ConcreteCreatorA(Creator): def factory_method(self): return ConcreteProductA() class ConcreteCreatorB(Creator): def factory_method(self): return ConcreteProductB() creator = ConcreteCreatorA()
product = creator.factory_method()
print(product.operation()) # Output: Result of ConcreteProductA
3. 抽象工厂模式(Abstract Factory)
目的:提供一个创建一系列相关或依赖对象的接口。
示例:
class AbstractFactory: def create_product_a(self): pass def create_product_b(self): pass class ConcreteFactory1(AbstractFactory): def create_product_a(self): return "Product A1" def create_product_b(self): return "Product B1" class ConcreteFactory2(AbstractFactory): def create_product_a(self): return "Product A2" def create_product_b(self): return "Product B2" factory = ConcreteFactory1()
print(factory.create_product_a()) # Output: Product A1
4. 建造者模式(Builder)
目的:将复杂对象的构建与表示分离,使同样的构建过程可以创建不同的表示。
示例:
class Product: def __init__(self): self.parts = [] def add(self, part): self.parts.append(part) class Builder: def __init__(self): self.product = Product() def build_part1(self): self.product.add("Part1") def build_part2(self): self.product.add("Part2") def get_product(self): return self.product builder = Builder()
builder.build_part1()
builder.build_part2()
product = builder.get_product()
print(product.parts) # Output: ['Part1', 'Part2']
5. 原型模式(Prototype)
目的:通过复制现有实例来创建新实例,而不是使用构造函数。
示例:
import copy class Prototype: def clone(self): return copy.deepcopy(self) class ConcretePrototype(Prototype): def __init__(self, value): self.value = value prototype = ConcretePrototype("Original")
clone = prototype.clone()
clone.value = "Clone"
print(prototype.value) # Output: Original
print(clone.value) # Output: Clone
二、结构型模式
1. 适配器模式(Adapter)
目的:将一个类的接口转换成客户希望的另一个接口。
示例:
class Target: def request(self): return "Target: Default behavior" class Adaptee: def specific_request(self): return "Adaptee: Specific behavior" 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()) # Output: Adaptee: Specific behavior
2. 桥接模式(Bridge)
目的:将抽象部分与其实现部分分离,以便可以独立变换。
示例:
class Abstraction: def __init__(self, implementor): self.implementor = implementor def operation(self): return f"Abstraction: {self.implementor.operation_impl()}" class Implementor: def operation_impl(self): return "Implementor" class ConcreteImplementorA(Implementor): def operation_impl(self): return "ConcreteImplementorA" implementor = ConcreteImplementorA()
abstraction = Abstraction(implementor)
print(abstraction.operation()) # Output: Abstraction: ConcreteImplementorA
3. 组合模式(Composite)
目的:将对象组合成树形结构以表示"部分-整体"的层次结构。
示例:
class Component: def operation(self): pass class Leaf(Component): def operation(self): return "Leaf" class Composite(Component): def __init__(self): self.children = [] def add(self, component): self.children.append(component) def operation(self): results = [child.operation() for child in self.children] return f"Composite: [{', '.join(results)}]" composite = Composite()
composite.add(Leaf())
composite.add(Leaf())
print(composite.operation()) # Output: Composite: [Leaf, Leaf]
4. 装饰模式(Decorator)
目的:动态地给对象添加一些额外的职责。
示例:
class Component: def operation(self): return "Basic Component" class Decorator(Component): def __init__(self, component): self.component = component def operation(self): return f"Decorator: {self.component.operation()}" decorated_component = Decorator(Component())
print(decorated_component.operation()) # Output: Decorator: Basic Component
5. 外观模式(Facade)
目的:为一个复杂子系统提供一个简单接口。
示例:
class Subsystem1: def operation1(self): return "Subsystem1: Ready" class Subsystem2: def operation2(self): return "Subsystem2: Ready" class Facade: def __init__(self): self.subsystem1 = Subsystem1() self.subsystem2 = Subsystem2() def operation(self): return f"{self.subsystem1.operation1()} and {self.subsystem2.operation2()}" facade = Facade()
print(facade.operation()) # Output: Subsystem1: Ready and Subsystem2: Ready
6. 享元模式(Flyweight)
目的:通过共享技术来尽量减少内存使用。
示例:
class Flyweight: def __init__(self, intrinsic_state): self.intrinsic_state = intrinsic_state def operation(self, extrinsic_state): return f"Intrinsic: {self.intrinsic_state}, Extrinsic: {extrinsic_state}" class FlyweightFactory: def __init__(self): self.flyweights = {} def get_flyweight(self, key): if key not in self.flyweights: self.flyweights[key] = Flyweight(key) return self.flyweights[key] factory = FlyweightFactory()
flyweight1 = factory.get_flyweight("X")
flyweight2 = factory.get_flyweight("Y")
print(flyweight1.operation("A")) # Output: Intrinsic: X, Extrinsic: A
7. 代理模式(Proxy)
目的:通过一个代理对象来控制对另一个对象的访问。
示例:
class RealSubject: def request(self): return "RealSubject: Handling request" class Proxy: def __init__(self): self.real_subject = RealSubject() def request(self): return f"Proxy: Forwarding request to {self.real_subject.request()}" proxy = Proxy()
print(proxy.request()) # Output: Proxy: Forwarding request to RealSubject: Handling request
三、行为型模式
1. 责任链模式(Chain of Responsibility)
目的:将请求的发送者与接收者解耦。
示例:
class Handler: def set_next(self, handler): self.next_handler = handler return handler def handle(self, request): if self.next_handler: return self.next_handler.handle(request) return None class ConcreteHandlerA(Handler): def handle(self, request): if request == "A": return "Handler A handled the request" return super().handle(request) class ConcreteHandlerB(Handler): def handle(self, request): if request == "B": return "Handler B handled the request" return super().handle(request) handler_a = ConcreteHandlerA()
handler_b = ConcreteHandlerB()
handler_a.set_next(handler_b) print(handler_a.handle("A")) # Output: Handler A handled the request
print(handler_a.handle("B")) # Output: Handler B handled the request
2. 命令模式(Command)
目的:将请求封装为一个对象,以便于参数化客户代码。
示例:
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): return "Receiver: Action executed" receiver = Receiver()
command = ConcreteCommand(receiver)
command.execute() # Output: Receiver: Action executed
3. 解释器模式(Interpreter)
目的:为语言定义一个文法,并提供一个解释器。
示例:
class Expression: def interpret(self, context): pass class TerminalExpression(Expression): def interpret(self, context): return context.split().count("Hello") context = "Hello world! Hello everyone!"
terminal = TerminalExpression()
print(terminal.interpret(context)) # Output: 2
4. 迭代器模式(Iterator)
目的:提供一种顺序访问聚合对象元素的方法,而无需暴露其内部表示。
示例:
class Iterator: def __init__(self, collection): self.collection = collection self.index = 0 def next(self): item = self.collection[self.index] self.index += 1 return item def has_next(self): return self.index < len(self.collection) collection = ["A", "B", "C"]
iterator = Iterator(collection)
while iterator.has_next(): print(iterator.next()) # Output: A, B, C
5. 中介者模式(Mediator)
目的:通过一个中介对象来减少对象之间的通信复杂度。
示例:
class Mediator: def notify(self, sender, event): pass class ConcreteMediator(Mediator): def __init__(self, component1, component2): self.component1 = component1 self.component2 = component2 def notify(self, sender, event): if sender == self.component1 and event == "A": self.component2.do_b() class Component1: def __init__(self, mediator): self.mediator = mediator def do_a(self): print("Component1: Doing A") self.mediator.notify(self, "A") class Component2: def __init__(self, mediator): self.mediator = mediator def do_b(self): print("Component2: Doing B") mediator = ConcreteMediator(Component1(mediator), Component2(mediator))
mediator.component1.do_a()
# Output:
# Component1: Doing A
# Component2: Doing B
6. 备忘录模式(Memento)
目的:在不暴露对象实现细节的情况下,捕获对象的内部状态。
示例:
class Memento: def __init__(self, state): self.state = state class Originator: def __init__(self): self.state = None def set_state(self, state): self.state = state def save(self): return Memento(self.state) def restore(self, memento): self.state = memento.state originator = Originator()
originator.set_state("State1")
memento = originator.save()
originator.set_state("State2")
originator.restore(memento)
print(originator.state) # Output: State1
7. 观察者模式(Observer)
目的:定义对象间的一对多依赖关系,使得当一个对象改变状态时,所有依赖于它的对象都会得到通知。
示例:
class Observer: def update(self, message): pass class ConcreteObserver(Observer): def update(self, message): print(f"Observer received: {message}") class Subject: def __init__(self): self.observers = [] def subscribe(self, observer): self.observers.append(observer) def unsubscribe(self, observer): self.observers.remove(observer) def notify(self, message): for observer in self.observers: observer.update(message) # 创建观察者和主题
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject = Subject() # 订阅观察者
subject.subscribe(observer1)
subject.subscribe(observer2) # 通知所有观察者
subject.notify("Hello Observers!")
# Output:
# Observer received: Hello Observers!
# Observer received: Hello Observers!
8. 状态模式(State)
目的:允许一个对象在其内部状态改变时改变其行为。
示例:
class State: def handle(self): pass class ConcreteStateA(State): def handle(self): return "State A: Handling" class ConcreteStateB(State): def handle(self): return "State B: Handling" 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()) # Output: State A: Handling context.set_state(ConcreteStateB())
print(context.request()) # Output: State B: Handling
9. 策略模式(Strategy)
目的:定义一系列算法,将每一个算法封装起来,并使它们可以互换。
示例:
class Strategy: def execute(self): pass class ConcreteStrategyA(Strategy): def execute(self): return "Strategy A executed!" class ConcreteStrategyB(Strategy): def execute(self): return "Strategy B executed!" class Context: def __init__(self, strategy): self.strategy = strategy def set_strategy(self, strategy): self.strategy = strategy def execute_strategy(self): return self.strategy.execute() context = Context(ConcreteStrategyA())
print(context.execute_strategy()) # Output: Strategy A executed! context.set_strategy(ConcreteStrategyB())
print(context.execute_strategy()) # Output: Strategy B executed!
10. 模板方法模式(Template Method)
目的:定义一个算法的框架,而将一些步骤延迟到子类中。
示例:
class AbstractClass: def template_method(self): self.step1() self.step2() def step1(self): pass def step2(self): pass class ConcreteClass(AbstractClass): def step1(self): return "Step 1 completed." def step2(self): return "Step 2 completed." concrete = ConcreteClass()
concrete.template_method()
# Output: Step 1 completed. Step 2 completed.
11. 访问者模式(Visitor)
目的:将操作封装到一个访问者对象中,以便于在不改变目标对象类的情况下增加新的操作。
示例:
class Element: def accept(self, visitor): pass class ConcreteElementA(Element): def accept(self, visitor): visitor.visit(self) class ConcreteElementB(Element): def accept(self, visitor): visitor.visit(self) class Visitor: def visit(self, element): pass class ConcreteVisitor(Visitor): def visit(self, element): return f"Visited {type(element).__name__}" elements = [ConcreteElementA(), ConcreteElementB()]
visitor = ConcreteVisitor() for element in elements: print(element.accept(visitor)) # Output: Visited ConcreteElementA Visited ConcreteElementB
以上是对观察者模式及其他行为型设计模式的详细介绍和示例。如果你还有其他问题或者想深入了解的内容,随时告诉我!