设计模式-行为型模式(模板方法、策略、观察者、迭代器、责任链、命令、状态、备忘录、访问者、中介者、解释器)

行为型模式:专注于对象之间的 协作 及如何通过彼此之间的交互来完成任务。行为型模式通常集中在描述对象之间的 责任 分配和 通信 机制,并提供了一些优雅解决特定问题的方案。

  1. 模板方法模式(Template Method Pattern)
  2. 策略模式(Strategy Pattern)
  3. 观察者模式(Observer Pattern)
  4. 迭代器模式(Iterator Pattern)
  5. 责任链模式(Chain of Responsibility Pattern)
  6. 命令模式(Command Pattern)
  7. 状态模式(State Pattern)
  8. 备忘录模式(Memento Pattern)
  9. 访问者模式(Visitor Pattern)
  10. 中介者模式(Mediator Pattern)
  11. 解释器模式(Interpreter Pattern)

模板方法模式(Template Method Pattern)

模板方法模式定义了一个算法骨架,将一些步骤延迟到子类中实现。这个模式使得子类可以不改变一个算法的结构即可重定义该算法的某些步骤。
from abc import ABC, abstractmethod


class Algorithm(ABC):
    def process_data(self, data):
        self.load_data(data)
        self.analyze_data()
        self.visualize_data()

    @abstractmethod
    def load_data(self, data):
        pass

    @abstractmethod
    def analyze_data(self):
        pass

    @abstractmethod
    def visualize_data(self):
        pass


class AudioProcessing(Algorithm):
    def load_data(self, data):
        print("Loading audio data...")

    def analyze_data(self):
        print("Analyzing audio data...")

    def visualize_data(self):
        print("Visualizing audio data...")


class ImageProcessing(Algorithm):
    def load_data(self, data):
        print("Loading image data...")

    def analyze_data(self):
        print("Analyzing image data...")

    def visualize_data(self):
        print("Visualizing image data...")


audio_processing = AudioProcessing()
image_processing = ImageProcessing()
audio_processing.process_data("Audio data")
image_processing.process_data("Image data")
"""
Loading audio data...
Analyzing audio data...
Visualizing audio data...
Loading image data...
Analyzing image data...
Visualizing image data...
"""

策略模式(Strategy Pattern)

策略模式定义了一系列算法,并将每个算法封装起来,再一个对外使用的类使得它们可以相互替换。
from abc import ABC, abstractmethod


class SortingStrategy(ABC):
    @abstractmethod
    def sort(self, data):
        pass


class MergeSort(SortingStrategy):
    def sort(self, data):
        print("Sorting data using merge sort...")


class QuickSort(SortingStrategy):
    def sort(self, data):
        print("Sorting data using quick sort...")


class BubbleSort(SortingStrategy):
    def sort(self, data):
        print("Sorting data using bubble sort...")


class Sorter:
    def __init__(self, sorting_strategy):
        self.sorting_strategy = sorting_strategy

    def set_sorting_strategy(self, sorting_strategy):
        self.sorting_strategy = sorting_strategy

    def sort_data(self, data):
        self.sorting_strategy.sort(data)


data = [5, 2, 4, 1, 3]
merge_sort = MergeSort()
quick_sort = QuickSort()
bubble_sort = BubbleSort()

sorter = Sorter(merge_sort)
sorter.sort_data(data)

sorter.set_sorting_strategy(quick_sort)
sorter.sort_data(data)

sorter.set_sorting_strategy(bubble_sort)
sorter.sort_data(data)
"""
Sorting data using merge sort...
Sorting data using quick sort...
Sorting data using bubble sort...
"""

观察者模式(Observer Pattern)

定义一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,并在主题对象变化时得到通知。这个模式使主题对象和观察者对象可以相互独立变化。
class Subject:
    def __init__(self):
        self.observers = []

    def add_observer(self, observer):
        self.observers.append(observer)

    def remove_observer(self, observer):
        self.observers.remove(observer)

    def notify_observers(self, data):
        for observer in self.observers:
            observer.update(data)


class Observer:
    def update(self, data):
        pass


class Sensor(Subject):
    def read_sensor_data(self):
        data = 42  # read sensor data here
        self.notify_observers(data)


class Display(Observer):
    def update(self, data):
        print(f"Displaying sensor data: {data}")


class Logging(Observer):
    def update(self, data):
        print(f"Logging sensor data: {data}")


sensor = Sensor()
display = Display()
logging = Logging()

sensor.add_observer(display)
sensor.add_observer(logging)

sensor.read_sensor_data()
"""
Displaying sensor data: 42
Logging sensor data: 42
"""

迭代器模式(Iterator Pattern)

提供一种方法来访问一个聚合对象中各个元素,而不需暴露该对象的内部表示。这个模式使得我们可以遍历一个聚合对象,而不用关心其内部结构。
class MyList:
    def __init__(self):
        self.data = []

    def add_item(self, item):
        self.data.append(item)

    def __iter__(self):
        return MyListIterator(self)


class MyListIterator:
    def __init__(self, my_list):
        self.my_list = my_list
        self.index = 0

    def __next__(self):
        if self.index >= len(self.my_list.data):
            raise StopIteration
        else:
            item = self.my_list.data[self.index]
            self.index += 1
            return item


my_list = MyList()
my_list.add_item("a")
my_list.add_item("b")
my_list.add_item("c")

for item in my_list:
    print(item)
'''
a
b
c
'''

责任链模式(Chain of Responsibility Pattern)

将请求的发送者和接收者解耦,使得多个对象都有机会处理这个请求。这个模式将这些对象组成一条链,并沿着该链传递该请求,直到有一个对象处理它为止。
from abc import ABC, abstractmethod


class Handler(ABC):
    def __init__(self, successor=None):
        self.successor = successor

    def handle_request(self, request):
        if self.can_handle_request(request):
            self.process_request(request)
        elif self.successor is not None:
            self.successor.handle_request(request)

    @abstractmethod
    def can_handle_request(self, request):
        pass

    @abstractmethod
    def process_request(self, request):
        pass


class ConcreteHandlerA(Handler):
    def can_handle_request(self, request):
        return request >= 0 and request < 3

    def process_request(self, request):
        print(f"Request {request} handled by ConcreteHandlerA")


class ConcreteHandlerB(Handler):
    def can_handle_request(self, request):
        return request >= 3 and request < 6

    def process_request(self, request):
        print(f"Request {request} handled by ConcreteHandlerB")


class ConcreteHandlerC(Handler):
    def can_handle_request(self, request):
        return request >= 6 and request < 9

    def process_request(self, request):
        print(f"Request {request} handled by ConcreteHandlerC")


handler_a = ConcreteHandlerA()
handler_b = ConcreteHandlerB()
handler_c = ConcreteHandlerC()

handler_a.successor = handler_b
handler_b.successor = handler_c

for request in range(1, 10):
    handler_a.handle_request(request)
"""
Request 1 handled by ConcreteHandlerA
Request 2 handled by ConcreteHandlerA
Request 3 handled by ConcreteHandlerB
Request 4 handled by ConcreteHandlerB
Request 5 handled by ConcreteHandlerB
Request 6 handled by ConcreteHandlerC
Request 7 handled by ConcreteHandlerC
Request 8 handled by ConcreteHandlerC
"""

命令模式(Command Pattern)

一个请求封装成一个对象,从而可将请求的发送者和接收者解耦。这个模式允许使用不同的请求来参数化对象,将请求排队或记录请求日志,以及支持可撤销的操作。
from abc import ABC, abstractmethod


class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def undo(self):
        pass


class Light:
    def on(self):
        print("Light is on")

    def off(self):
        print("Light is off")


class LightOnCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.on()

    def undo(self):
        self.light.off()


class LightOffCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.off()

    def undo(self):
        self.light.on()


class RemoteControl:
    def __init__(self):
        self.commands = []

    def add_command(self, command):
        self.commands.append(command)

    def execute_commands(self):
        for command in self.commands:
            command.execute()


light = Light()
light_on_command = LightOnCommand(light)
light_off_command = LightOffCommand(light)

remote_control = RemoteControl()
remote_control.add_command(light_on_command)
remote_control.add_command(light_off_command)

remote_control.execute_commands()
"""
Light is on
Light is off
"""

状态模式(State Pattern)

允许对象在其内部状态发生改变时改变它的行为。这个模式将一个对象的状态从该对象中移出来,并将其封装到不同的状态对象中。
from abc import ABC, abstractmethod


class State(ABC):
    @abstractmethod
    def handle(self):
        pass


class ConcreteStateA(State):
    def handle(self):
        print("Handling state A")
        return ConcreteStateB()


class ConcreteStateB(State):
    def handle(self):
        print("Handling state B")
        return ConcreteStateC()


class ConcreteStateC(State):
    def handle(self):
        print("Handling state C")
        return ConcreteStateA()


class Context:
    def __init__(self, initial_state):
        self.state = initial_state

    def request(self):
        self.state = self.state.handle()


context = Context(ConcreteStateA())
context.request()
context.request()
context.request()
"""
Handling state A
Handling state B
Handling state C
"""

备忘录模式(Memento Pattern)

允许在不破坏封装性的前提下,捕获并保存一个对象的内部状态,以便可以将该对象恢复到原先保存的状态。这个模式通常用于需要撤销操作的场景。
class Memento:  # 一个类记录状态返回状态
    def __init__(self, state):
        self.state = state

    def get_state(self):
        return self.state


class Originator:
    def __init__(self, state):
        self.state = state

    def create_memento(self):
        return Memento(self.state)

    def restore_memento(self, memento):
        self.state = memento.get_state()

    def set_state(self, state):
        self.state = state

    def get_state(self):
        return self.state


class Caretaker:
    def __init__(self, originator):
        self.mementos = []
        self.originator = originator

    def save_state(self):
        memento = self.originator.create_memento()
        self.mementos.append(memento)

    def restore_last_state(self):
        if len(self.mementos) > 0:
            memento = self.mementos.pop()
            self.originator.restore_memento(memento)


originator = Originator("State A")
caretaker = Caretaker(originator)

print(originator.get_state())
caretaker.save_state()

originator.set_state("State B")
print(originator.get_state())

caretaker.save_state()
originator.set_state("State C")
print(originator.get_state())

caretaker.restore_last_state()
print(originator.get_state())

caretaker.restore_last_state()
print(originator.get_state())
"""
State A
State B
State C
State B
State A
"""

访问者模式(Visitor Pattern)

定义了一种新的操作方式,可在不改变一个对象的类的前提下,向该对象添加新的操作。这个模式通常用于需对一个复杂的对象结构进行处理的场景。
from abc import ABC, abstractmethod


class Visitor(ABC):
    @abstractmethod
    def visit_element_a(self, element_a):
        pass

    @abstractmethod
    def visit_element_b(self, element_b):
        pass


class Element(ABC):
    @abstractmethod
    def accept(self, visitor):
        pass


class ConcreteElementA(Element):  # 新操作
    def accept(self, visitor):
        visitor.visit_element_a(self)


class ConcreteElementB(Element):  # 新操作
    def accept(self, visitor):
        visitor.visit_element_b(self)


class ConcreteVisitor1(Visitor):
    def visit_element_a(self, element_a):
        print("ConcreteVisitor1 visiting ConcreteElementA")

    def visit_element_b(self, element_b):
        print("ConcreteVisitor1 visiting ConcreteElementB")


class ConcreteVisitor2(Visitor):
    def visit_element_a(self, element_a):
        print("ConcreteVisitor2 visiting ConcreteElementA")

    def visit_element_b(self, element_b):
        print("ConcreteVisitor2 visiting ConcreteElementB")


elements = [ConcreteElementA(), ConcreteElementB()]
visitors = [ConcreteVisitor1(), ConcreteVisitor2()]

for element in elements:
    for visitor in visitors:
        element.accept(visitor)
'''
ConcreteVisitor1 visiting ConcreteElementA
ConcreteVisitor2 visiting ConcreteElementA
ConcreteVisitor1 visiting ConcreteElementB
ConcreteVisitor2 visiting ConcreteElementB
'''

中介者模式(Mediator Pattern)

定义了一个中介对象来封装一系列对象之间的交互。这个模式使得各对象之间不需要显式地相互引用,从而使其耦合度降低,同时也有助于复杂系统的维护。
from abc import ABC, abstractmethod


class Colleague(ABC):
    def __init__(self, mediator):
        self.mediator = mediator

    @abstractmethod
    def send(self, message):
        pass

    @abstractmethod
    def receive(self, message):
        pass


class ConcreteColleagueA(Colleague):
    def send(self, message):
        self.mediator.send_message(message, self)

    def receive(self, message):
        print(f"ConcreteColleagueA received message: {message}")


class ConcreteColleagueB(Colleague):
    def send(self, message):
        self.mediator.send_message(message, self)

    def receive(self, message):
        print(f"ConcreteColleagueB received message: {message}")


class Mediator:
    def __init__(self):
        self.colleagues = []

    def add_colleague(self, colleague):
        self.colleagues.append(colleague)

    def send_message(self, message, sender):
        for colleague in self.colleagues:
            if colleague != sender:
                colleague.receive(message)


mediator = Mediator()
# 创建
colleague_a = ConcreteColleagueA(mediator)
colleague_b = ConcreteColleagueB(mediator)
# 注册
mediator.add_colleague(colleague_a)
mediator.add_colleague(colleague_b)
# 通过中介对象
colleague_a.send("Hello, colleague B")
colleague_b.send("Hi, colleague A")
"""
ConcreteColleagueB received message: Hello, colleague B
ConcreteColleagueA received message: Hi, colleague A
"""

解释器模式(Interpreter Pattern)

定义了一个语言的文法,且建立一个解释器来解释该语言中的句子。这个模式常用于需对一些特定语言进行处理或解析的场景。
from abc import ABC, abstractmethod


class Expression(ABC):
    @abstractmethod
    def interpret(self):
        pass


class NumberExpression(Expression):
    def __init__(self, number):
        self.number = number

    def interpret(self):
        return self.number


class PlusExpression(Expression):
    def __init__(self, expression1, expression2):
        self.expression1 = expression1
        self.expression2 = expression2

    def interpret(self):
        return self.expression1.interpret() + self.expression2.interpret()


class MinusExpression(Expression):
    def __init__(self, expression1, expression2):
        self.expression1 = expression1
        self.expression2 = expression2

    def interpret(self):
        return self.expression1.interpret() - self.expression2.interpret()


expression = MinusExpression(
    PlusExpression(NumberExpression(5), NumberExpression(3)),
    NumberExpression(2)
)

print(expression.interpret())  # 6

你可能感兴趣的:(设计模式,设计模式)