Python的設(shè)計(jì)模式:構(gòu)建更優(yōu)雅的代碼
設(shè)計(jì)模式是在軟件工程中廣泛使用的經(jīng)驗(yàn)豐富的解決問(wèn)題的方法。它們是通用的、可重復(fù)使用的解決方案,用于解決常見(jiàn)的設(shè)計(jì)問(wèn)題。設(shè)計(jì)模式有助于使代碼更易于理解、可維護(hù)和可擴(kuò)展。Python作為一門多范式的編程語(yǔ)言,提供了豐富的設(shè)計(jì)模式應(yīng)用場(chǎng)景。
在本文中,我們將詳細(xì)介紹 Python 中的各種設(shè)計(jì)模式,包括創(chuàng)建型、結(jié)構(gòu)型和行為型模式。
創(chuàng)建型模式
創(chuàng)建型模式關(guān)注對(duì)象的創(chuàng)建機(jī)制,它們包括單例、工廠、抽象工廠、建造者和原型模式。這些模式旨在提供一種靈活的方式來(lái)創(chuàng)建對(duì)象,同時(shí)減少對(duì)象創(chuàng)建的復(fù)雜性。
單例模式
單例模式確保一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)。這對(duì)于需要在應(yīng)用程序中共享資源的情況非常有用,例如配置管理、日志記錄和數(shù)據(jù)庫(kù)連接。
示例代碼:
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) # 輸出:True
單例模式確保只創(chuàng)建一個(gè)實(shí)例,即使多次創(chuàng)建也返回相同的實(shí)例。
工廠模式
工廠模式用于創(chuàng)建對(duì)象,將對(duì)象的創(chuàng)建邏輯封裝在一個(gè)方法中,從而實(shí)現(xiàn)對(duì)象的創(chuàng)建和使用的解耦。工廠模式可以根據(jù)傳入的參數(shù)選擇創(chuàng)建哪種類型的對(duì)象。
示例代碼:
class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, name):
self.name = name
class AnimalFactory:
def create_animal(self, animal_type, name):
if animal_type == "dog":
return Dog(name)
elif animal_type == "cat":
return Cat(name)
# 使用工廠模式
factory = AnimalFactory()
dog = factory.create_animal("dog", "Buddy")
cat = factory.create_animal("cat", "Whiskers")
工廠模式將對(duì)象創(chuàng)建的邏輯封裝在一個(gè)工廠類中,客戶端可以根據(jù)需要?jiǎng)?chuàng)建不同類型的對(duì)象。
抽象工廠模式
抽象工廠模式提供了一種創(chuàng)建相關(guān)對(duì)象家族的方式,而無(wú)需指定它們的具體類。這允許創(chuàng)建一組相關(guān)對(duì)象,例如不同操作系統(tǒng)下的窗口和按鈕。
示例代碼:
class Button:
def display(self):
pass
class Window:
def display(self):
pass
class MacOSButton(Button):
def display(self):
print("MacOS Button")
class LinuxButton(Button):
def display(self):
print("Linux Button")
class MacOSWindow(Window):
def display(self):
print("MacOS Window")
class LinuxWindow(Window):
def display(self):
print("Linux Window")
class GUIFactory:
def create_button(self):
pass
def create_window(self):
pass
class MacOSFactory(GUIFactory):
def create_button(self):
return MacOSButton()
def create_window(self):
return MacOSWindow()
class LinuxFactory(GUIFactory):
def create_button(self):
return LinuxButton()
def create_window(self):
return LinuxWindow()
# 使用抽象工廠模式
macos_factory = MacOSFactory()
linux_factory = LinuxFactory()
macos_button = macos_factory.create_button()
linux_window = linux_factory.create_window()
macos_button.display() # 輸出:MacOS Button
linux_window.display() # 輸出:Linux Window
抽象工廠模式創(chuàng)建一組相關(guān)的對(duì)象,例如在不同操作系統(tǒng)下使用不同樣式的界面組件。
建造者模式
建造者模式將一個(gè)復(fù)雜對(duì)象的構(gòu)建過(guò)程分解為一系列步驟,使客戶端能夠按步驟構(gòu)建對(duì)象。這對(duì)于構(gòu)建包含許多可選組件的對(duì)象非常有用。
示例代碼:
class Pizza:
def __init__(self, size, cheese, pepperoni, mushrooms):
self.size = size
self.cheese = cheese
self.pepperoni = pepperoni
self.mushrooms = mushrooms
class PizzaBuilder:
def __init__(self, size):
self.size = size
self.cheese = False
self.pepperoni = False
self.mushrooms = False
def add_cheese(self):
self.cheese = True
return self
def add_pepperoni(self):
self.pepperoni = True
return self
def add_mushrooms(self):
self.mushrooms = True
return self
def build(self):
return Pizza(self.size, self.cheese, self.pepperoni, self.mushrooms)
# 使用建造者模式
pizza = PizzaBuilder(12).add_cheese().add_pepperoni().build()
建造者模式逐步構(gòu)建一個(gè)對(duì)象,設(shè)置其屬性并最終構(gòu)建對(duì)象。這對(duì)于構(gòu)建參數(shù)眾多的對(duì)象非常有用。
原型模式
原型模式通過(guò)復(fù)制現(xiàn)有對(duì)象來(lái)創(chuàng)建新對(duì)象。這對(duì)于創(chuàng)建大型對(duì)象或需要定制初始化的對(duì)象非常有用。原型模式可以克隆一個(gè)現(xiàn)有對(duì)象,而無(wú)需從頭創(chuàng)建一個(gè)新對(duì)象。
示例代碼:
import copy
class Prototype:
def __init__(self):
self.items = []
def clone(self):
return copy.deepcopy(self)
# 使用原型模式
original = Prototype()
original.items.append("item1")
# 克隆原型對(duì)象
clone = original.clone()
clone.items.append("item2")
print(original.items) # 輸出:['item1']
print(clone.items) # 輸出:['item1', 'item2']
原型模式可以克隆對(duì)象,能夠在不從頭創(chuàng)建對(duì)象的情況下生成新對(duì)象。
結(jié)構(gòu)型模式
結(jié)構(gòu)型模式處理對(duì)象之間的關(guān)系,包括適配器、橋接、組合、裝飾器、外觀、享元和代理模式。這些模式有助于定義對(duì)象之間的協(xié)作方式,同時(shí)保持系統(tǒng)的靈活性和可維護(hù)性。
適配器模式
適配器模式用于將一個(gè)接口轉(zhuǎn)換成另一個(gè)接口,以使不兼容的類可以一起工作。適配器模式使用不同接口的對(duì)象協(xié)同工作。
示例代碼:
class OldSystem:
def operation(self):
return "Old System"
class NewSystem:
def operation(self):
return "New System"
class Adapter:
def __init__(self, new_system):
self.new_system = new_system
def operation(self):
return f"Adapter using {self.new_system.operation()}"
# 使用適配器模式
new_system = NewSystem()
adapter = Adapter(new_system)
result = adapter.operation()
print(result) # 輸出:Adapter using New System
適配器模式允許新舊系統(tǒng)一起工作,將新系統(tǒng)的接口適配為舊系統(tǒng)可以使用的接口。
橋接模式
橋接模式將抽象部分與實(shí)現(xiàn)部分分離,它們可以獨(dú)立變化。這有助于減少類之間的耦合,同時(shí)允許它們?cè)谶\(yùn)行時(shí)獨(dú)立變化。
示例代碼:
class DrawingAPI:
def draw_circle(self, x, y, radius):
pass
class DrawingAPI1(DrawingAPI):
def draw_circle(self, x, y, radius):
print(f"API1.circle at {x}:{y} radius {radius}")
class DrawingAPI2(DrawingAPI):
def draw_circle(self, x, y, radius):
print(f"API2.circle at {x}:{y} radius {radius}")
class Shape:
def __init__(self, drawing_api):
self.drawing_api = drawing_api
def draw(self):
pass
class Circle(Shape):
def __init__(self, x, y, radius, drawing_api):
super().__init__(drawing_api)
self.x = x
self.y = y
self.radius = radius
def draw(self):
self.drawing_api.draw_circle(self.x, self.y, self.radius)
# 使用橋接模式
api1 = DrawingAPI1()
api2 = DrawingAPI2()
circle1 = Circle(1, 2, 3, api1)
circle1.draw() # 輸出
:API1.circle at 1:2 radius 3
circle2 = Circle(4, 5, 6, api2)
circle2.draw() # 輸出:API2.circle at 4:5 radius 6
橋接模式將抽象形狀和繪制API分開(kāi),使它們可以獨(dú)立變化。這有助于降低系統(tǒng)的復(fù)雜性。
組合模式
組合模式用于將對(duì)象組織成樹(shù)狀結(jié)構(gòu),以表示部分-整體關(guān)系。這使得客戶端可以統(tǒng)一處理單個(gè)對(duì)象和組合對(duì)象,從而簡(jiǎn)化代碼。
示例代碼:
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 = []
for child in self.children:
results.append(child.operation())
return f"Composite [{', '.join(results)}]"
# 使用組合模式
leaf1 = Leaf()
leaf2 = Leaf()
composite = Composite()
composite.add(leaf1)
composite.add(leaf2)
result = composite.operation()
print(result) # 輸出:Composite [Leaf, Leaf]
組合模式允許構(gòu)建包含子組件的復(fù)雜對(duì)象,同時(shí)使客戶端能夠一致地處理單個(gè)對(duì)象和組合對(duì)象。
裝飾器模式
裝飾器模式動(dòng)態(tài)地將責(zé)任附加到對(duì)象上。它是在不修改對(duì)象源代碼的情況下擴(kuò)展對(duì)象功能的一種方式。
示例代碼:
class Coffee:
def cost(self):
return 5
class MilkDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 2
class SugarDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 1
# 使用裝飾器模式
coffee = Coffee()
print(coffee.cost()) # 輸出:5
coffee_with_milk = MilkDecorator(coffee)
print(coffee_with_milk.cost()) # 輸出:7
coffee_with_milk_and_sugar = SugarDecorator(coffee_with_milk)
print(coffee_with_milk_and_sugar.cost()) # 輸出:8
裝飾器模式在運(yùn)行時(shí)動(dòng)態(tài)地添加新功能或修改對(duì)象的行為。
外觀模式
外觀模式提供了一個(gè)統(tǒng)一的接口,用于訪問(wèn)子系統(tǒng)中的一組接口。這簡(jiǎn)化了復(fù)雜子系統(tǒng)的使用,為客戶端提供了一個(gè)簡(jiǎn)化的接口。
示例代碼:
class SubsystemA:
def operation_a(self):
return "Subsystem A operation"
class SubsystemB:
def operation_b(self):
return "Subsystem B operation"
class SubsystemC:
def operation_c(self):
return "Subsystem C operation"
class Facade:
def __init__(self):
self.subsystem_a = SubsystemA()
self.subsystem_b = SubsystemB()
self.subsystem_c = SubsystemC()
def operation(self):
result = []
result.append(self.subsystem_a.operation_a())
result.append(self.subsystem_b.operation_b())
result.append(self.subsystem_c.operation_c())
return "\n".join(result)
# 使用外觀模式
facade = Facade()
result = facade.operation()
print(result)
外觀模式提供了一個(gè)高級(jí)接口,使客戶端能夠訪問(wèn)一組子系統(tǒng)接口,而不必了解其復(fù)雜性。
享元模式
享元模式用于共享大量細(xì)粒度對(duì)象,以減少內(nèi)存占用。它將對(duì)象的共享部分抽象出來(lái),以減少對(duì)象的數(shù)量。
示例代碼:
class Flyweight:
def operation(self):
pass
class ConcreteFlyweight(Flyweight):
def __init__(self, intrinsic_state):
self._intrinsic_state = intrinsic_state
def operation(self):
return f"Concrete Flyweight: {self._intrinsic_state}"
class FlyweightFactory:
def __init__(self):
self._flyweights = {}
def get_flyweight(self, key):
if key not in self._flyweights:
self._flyweights[key] = ConcreteFlyweight(key)
return self._flyweights[key]
# 使用享元模式
factory = FlyweightFactory()
flyweight1 = factory.get_flyweight("A")
flyweight2 = factory.get_flyweight("B")
print(flyweight1.operation()) # 輸出:Concrete Flyweight: A
print(flyweight2.operation()) # 輸出:Concrete Flyweight: B
享元模式允許多個(gè)對(duì)象共享相同的內(nèi)部狀態(tài),從而降低內(nèi)存占用。
代理模式
代理模式允許創(chuàng)建一個(gè)代理對(duì)象,用于控制對(duì)其他對(duì)象的訪問(wèn)。代理對(duì)象充當(dāng)被代理對(duì)象的接口,以便在不直接訪問(wèn)被代理對(duì)象的情況下執(zhí)行其他操作。
示例代碼:
class Subject:
def operation(self):
pass
class RealSubject(Subject):
def operation(self):
return "Real Subject operation"
class Proxy(Subject):
def __init__(self):
self._real_subject = RealSubject()
def operation(self):
return f"Proxy operation, {self._real_subject.operation()}"
# 使用代理模式
proxy = Proxy()
result = proxy.operation()
print(result) # 輸出:Proxy operation, Real Subject operation
代理模式允許代理對(duì)象控制對(duì)真實(shí)對(duì)象的訪問(wèn),從而提供附加的功能或控制。
行為型模式
行為型模式處理對(duì)象之間的通信,包括觀察者、策略、命令、責(zé)任鏈、狀態(tài)、訪問(wèn)者、迭代器、備忘錄、中介者、解釋器和模板方法模式。這些模式有助于定義對(duì)象之間的交互和職責(zé)分配。
觀察者模式
觀察者模式定義了一種一對(duì)多的依賴關(guān)系,其中一個(gè)對(duì)象的狀態(tài)發(fā)生變化時(shí),其所有依賴對(duì)象都會(huì)得到通知。
示例代碼:
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update()
class ConcreteSubject(Subject):
def __init__(self, state):
super().__init__()
self._state = state
def get_state(self):
return self._state
def set_state(self, state):
self._state = state
self.notify()
class Observer:
def update(self):
pass
class ConcreteObserver(Observer):
def __init__(self, subject):
self._subject = subject
self._state = subject.get_state()
def update(self):
self._state = self._subject.get_state()
# 使用觀察者模式
subject = ConcreteSubject("initial state")
observer1 = ConcreteObserver(subject)
observer2 = ConcreteObserver(subject)
subject.attach(observer1)
subject.attach(observer2)
print(observer1._state) # 輸出:initial state
print(observer2._state) # 輸出:initial state
subject.set_state("new state")
print(observer1._state) # 輸出:new state
print(observer2._state) # 輸出:new state
觀察者模式允許主題對(duì)象和觀察者對(duì)象之間保持松散的耦合,主題對(duì)象的狀態(tài)變化會(huì)自動(dòng)通知觀察者對(duì)象。
策略模式
策略模式定義了一系列算法,封裝每個(gè)算法,并使它們可以相互替換。這提供了靈活性,允許在運(yùn)行時(shí)選擇算法。
示例代碼:
class Strategy:
def execute(self, a, b):
pass
class AddStrategy(Strategy):
def execute(self, a, b):
return a + b
class SubtractStrategy(Strategy):
def execute(self, a, b):
return a - b
class Calculator:
def __init__(self, strategy):
self._strategy = strategy
def execute(self, a, b):
return self._strategy.execute(a, b)
# 使用策略模式
add_strategy = AddStrategy()
sub_strategy = SubtractStrategy()
calculator = Calculator(add_strategy)
result = calculator.execute(5, 3)
print(result) # 輸出:8
calculator = Calculator(sub_strategy)
result = calculator.execute(5, 3)
print(result) # 輸出:2
策略模式允許定義一組算法,并將它們封裝在可互換的策略對(duì)象中,以便在運(yùn)行時(shí)選擇不同的算法。
命令模式
命令模式將請(qǐng)求封裝成一個(gè)對(duì)象,從而可以參數(shù)化客戶端對(duì)象操作,隊(duì)列請(qǐng)求或記錄請(qǐng)求日志。
示例代碼:
class Receiver:
def action(self):
pass
class Light(Receiver):
def action(self):
print("Light is on")
class Stereo(Receiver):
def action(self):
print("Stereo is on")
class Command:
def __init__(self, receiver):
self._receiver = receiver
def execute(self):
pass
class LightOnCommand(Command):
def execute(self):
self._receiver.action()
class StereoOnCommand(Command):
def execute(self):
self._receiver.action()
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()
stereo = Stereo()
light_on_command = LightOnCommand(light)
stereo_on_command = StereoOnCommand(stereo)
remote = RemoteControl()
remote.add_command(light_on_command)
remote.add_command(stereo_on_command)
remote.execute_commands()
# 輸出:
# Light is on
# Stereo is on
命令模式將請(qǐng)求和處理請(qǐng)求的對(duì)象解耦,允許將命令存儲(chǔ)、排隊(duì)和操作。
責(zé)任鏈模式
責(zé)任鏈模式構(gòu)建一系列對(duì)象,每個(gè)對(duì)象負(fù)責(zé)處理請(qǐng)求的一部分。請(qǐng)求按順序通過(guò)鏈傳遞,直到有一個(gè)對(duì)象處理它為止。
示例代碼:
class Handler:
def set_successor(self, successor):
self._successor = successor
def handle_request(self, request):
pass
class ConcreteHandler1(Handler):
def handle_request(self, request):
if request == "A":
return "Handled by Handler1"
elif self._successor:
return self._successor.handle_request(request)
else:
return "Request not handled"
class ConcreteHandler2(Handler):
def handle_request(self, request):
if request == "B":
return "Handled by Handler2"
elif self._successor:
return self._successor.handle_request(request)
else:
return "Request not handled"
# 使用責(zé)任鏈模式
handler1 = ConcreteHandler1()
handler2 = ConcreteHandler2()
handler1.set_successor(handler2)
result1 = handler1.handle_request("A")
print(result1) # 輸出:Handled by Handler1
result2 = handler1.handle_request("B")
print(result2) # 輸出:Handled by Handler2
result3 = handler1.handle_request("C")
print(result3) # 輸出:Request not handled
責(zé)任鏈模式允許構(gòu)建對(duì)象鏈,其中每個(gè)對(duì)象決定是否處理請(qǐng)求或?qū)⑵鋫鬟f給下一個(gè)對(duì)象。
狀態(tài)模式
狀態(tài)模式允許對(duì)象在其內(nèi)部狀態(tài)改變時(shí)改變其行為。這將狀態(tài)轉(zhuǎn)移邏輯封裝在不同的狀態(tài)類中。
示例代碼:
class State:
def handle(self):
pass
class StateA(State):
def handle(self):
return "State A"
class StateB(State):
def handle(self):
return "State B"
class Context:
def __init__(self):
self._state = None
def set_state(self, state):
self._state = state
def request(self):
return self._state.handle()
# 使用狀態(tài)模式
context = Context()
state_a = StateA()
state_b = StateB()
context.set_state(state_a)
result1 = context.request()
print(result1) # 輸出:State A
context.set_state(state_b)
result2 = context.request()
print(result2) # 輸出:State B
狀態(tài)模式允許對(duì)象在其內(nèi)部狀態(tài)改變時(shí)改變其行為,從而使其看起來(lái)像是更改了類。
訪問(wèn)者模式
訪問(wèn)者模式允許在不修改對(duì)象結(jié)構(gòu)的情況下為對(duì)象結(jié)構(gòu)中的元素添加新操作。它通過(guò)將訪問(wèn)操作從元素類中分離出來(lái)來(lái)實(shí)現(xiàn)這一點(diǎn)。
示例代碼:
class Element:
def accept(self, visitor):
pass
class ConcreteElementA(Element):
def accept(self, visitor):
visitor.visit_concrete_element_a(self)
class ConcreteElementB(Element):
def accept(self, visitor):
visitor.visit_concrete_element_b(self)
class Visitor:
def visit_concrete_element_a(self, element):
pass
def visit_concrete_element_b(self, element):
pass
class ConcreteVisitor(Visitor):
def visit_concrete_element_a(self, element):
return f"Visited {element.__class__.__name__} by {self.__class__.__name__}"
def visit_concrete_element_b(self, element):
return f"Visited {element.__class__.__name__} by {self.__class__.__name__}"
# 使用訪問(wèn)者模式
element_a = ConcreteElementA()
element_b = ConcreteElementB()
visitor = ConcreteVisitor()
result1 = element_a.accept(visitor)
print(result1) # 輸出:Visited ConcreteElementA by ConcreteVisitor
result2 = element_b.accept(visitor)
print(result2) # 輸出:Visited ConcreteElementB by ConcreteVisitor
訪問(wèn)者模式將元素和訪問(wèn)操作分離,為元素添加新操作而無(wú)需修改元素類。
迭代器模式
迭代器模式在不暴露集合的內(nèi)部表示的情況下順序訪問(wèn)集合的元素。
示例代碼:
class Iterator:
def next(self):
pass
class Aggregate:
def create_iterator(self):
pass
class ConcreteIterator(Iterator):
def __init__(self, collection):
self._collection = collection
self._index = 0
def next(self):
if self._index < len(self._collection):
item = self._collection[self._index]
self._index += 1
return item
else:
raise StopIteration()
class ConcreteAggregate(Aggregate):
def __init__(self):
self._collection = []
def create_iterator(self):
return ConcreteIterator(self._collection)
def add_item(self, item):
self._collection.append(item)
# 使用迭代器模式
aggregate = ConcreteAggregate()
aggregate.add_item("Item 1")
aggregate.add_item("Item 2")
aggregate.add_item("Item 3")
iterator = aggregate.create_iterator()
while True:
try:
item = iterator.next()
print(item)
except StopIteration:
break
迭代器模式順序訪問(wèn)集合的元素,而無(wú)需暴露其內(nèi)部表示。
備忘錄模式
備忘錄模式用于捕獲一個(gè)對(duì)象的內(nèi)部狀態(tài),以便以后可以將其恢復(fù)到該狀態(tài)。它將對(duì)象狀態(tài)的保存和恢復(fù)分離開(kāi)來(lái)。
示例代碼:
class Memento:
def __init__(self, state):
self._state = state
def get_state(self):
return self._state
class Originator:
def __init__(self):
self._state = ""
def set_state(self, state):
self._state = state
def create_memento(self):
return Memento(self._state)
def restore_memento(self, memento):
self._state = memento.get_state()
class Caretaker:
def __init__(self):
self._mementos = []
def add_memento(self, memento):
self._mementos.append(memento)
def get_memento(self, index):
return self._mementos[index]
# 使用備忘錄模式
originator = Originator()
caretaker = Caretaker()
originator.set_state("State 1")
caretaker.add_memento(originator.create_memento())
originator.set_state("State 2")
caretaker.add_memento(originator.create_memento())
originator.restore_memento(caretaker.get_memento(0))
print(originator._state) # 輸出:State 1
originator.restore_memento(caretaker.get_memento(1))
print(originator._state) # 輸出:State 2
備忘錄模式保存對(duì)象的狀態(tài),并在需要時(shí)將其恢復(fù)到以前的狀態(tài)。
中介者模式
中介者模式用于減少對(duì)象之間的直接通信,將對(duì)象之間的交互集中到中介者對(duì)象中。這有助于減少對(duì)象之間的耦合。
示例代碼:
class Mediator:
def send(self, message, colleague):
pass
class Colleague:
def __init__(self, mediator):
self._mediator = mediator
def send(self, message):
self._mediator.send(message, self)
class ConcreteMediator(Mediator):
def __init__(self, colleague1, colleague2):
self._colleague1 = colleague1
self._colleague2 = colleague2
def send(self, message, colleague):
if colleague == self._colleague1:
self._colleague2.receive(message)
else:
self._colleague1.receive(message)
class ConcreteColleague1(Colleague):
def receive(self, message):
print(f"Colleague 1 received: {message}")
class ConcreteColleague2(Colleague):
def receive(self, message):
print(f"Colleague 2 received: {message}")
# 使用中介者模式
colleague1 = ConcreteColleague1(None)
colleague2 = ConcreteColleague2(None)
mediator = ConcreteMediator(colleague1, colleague2)
colleague1._mediator = mediator
colleague2._mediator = mediator
colleague1.send("Hello from Colleague 1")
colleague2.send("Hi from Colleague 2")
中介者模式將對(duì)象之間的通信集中到中介者對(duì)象中,減少了對(duì)象之間的直接耦合。
解釋器模式
解釋器模式用于定義一門語(yǔ)言的語(yǔ)法,以解釋語(yǔ)言中的句子。它將語(yǔ)法規(guī)則和解釋邏輯分開(kāi)。
示例代碼:
class Expression:
def interpret(self):
pass
class TerminalExpression(Expression):
def __init__(self, data):
self._data = data
def interpret(self):
if self._data in ["LiteralA", "LiteralB"]:
return True
return False
class OrExpression(Expression):
def __init__(self, expression1, expression2):
self._expression1 = expression1
self._expression2 = expression2
def interpret(self):
return self._expression1.interpret() or self._expression2.interpret()
class AndExpression(Expression):
def __init__(self, expression1, expression2):
self._expression1 = expression1
self._expression2 = expression2
def interpret(self):
return self._expression1.interpret() and self._expression2.interpret()
# 使用解釋器模式
expression1 = TerminalExpression("LiteralA")
expression2 = TerminalExpression("LiteralB")
or_expression = OrExpression(expression1, expression2)
and_expression = AndExpression(expression1, expression2)
result1 = or_expression.interpret()
print(result1) # 輸出:True
result2 = and_expression.interpret()
print(result2) # 輸出:True
解釋器模式定義一門語(yǔ)言的語(yǔ)法,并為語(yǔ)言中的句子創(chuàng)建解釋器。
模板方法模式
模板方法模式定義了一個(gè)算法的骨架,將算法的一些步驟推遲到子類中。這允許子類在不改變算法結(jié)構(gòu)的情況下重新定義算法的某些步驟。
示例代碼:
class AbstractClass:
def template_method(self):
self.operation1()
self.operation2()
def operation1(self):
pass
def operation2(self):
pass
class ConcreteClass1(AbstractClass):
def operation1(self):
print("ConcreteClass1: Operation 1")
def operation2(self):
print("ConcreteClass1: Operation 2")
class ConcreteClass2(AbstractClass):
def operation1(self):
print("ConcreteClass2: Operation 1")
def operation2(self):
print("ConcreteClass2: Operation 2")
# 使用模板方法模式
concrete1 = ConcreteClass1()
concrete1.template_method()
# 輸出:
# ConcreteClass1: Operation 1
# ConcreteClass1: Operation 2
concrete2 = ConcreteClass2()
concrete2.template_method()
# 輸出:
# ConcreteClass2: Operation 1
# ConcreteClass2: Operation 2
模板方法模式定義了一個(gè)算法的骨架,允許子類提供實(shí)現(xiàn)特定步驟的方法。
結(jié)論
Python的設(shè)計(jì)模式是一種有關(guān)如何解決特定問(wèn)題或設(shè)計(jì)靈活可維護(hù)代碼的指導(dǎo)原則。設(shè)計(jì)模式是開(kāi)發(fā)者們多年經(jīng)驗(yàn)的總結(jié),可以在面對(duì)各種軟件設(shè)計(jì)挑戰(zhàn)時(shí)提供有力的解決方案。
創(chuàng)建型設(shè)計(jì)模式處理對(duì)象的創(chuàng)建,包括單例、工廠、抽象工廠、建造者和原型模式。這些模式可以靈活地管理對(duì)象的生命周期和創(chuàng)建過(guò)程。
結(jié)構(gòu)型設(shè)計(jì)模式有助于組織和管理對(duì)象之間的關(guān)系,包括適配器、裝飾器、代理、組合、橋接、享元和外觀模式。它們構(gòu)建更靈活和可維護(hù)的系統(tǒng)。
行為型設(shè)計(jì)模式處理對(duì)象之間的通信和協(xié)作,包括觀察者、策略、命令、責(zé)任鏈、狀態(tài)、訪問(wèn)者、迭代器、備忘錄、中介者、解釋器和模板方法模式。這些模式有助于定義對(duì)象之間的交互和協(xié)作方式。
設(shè)計(jì)模式可以提高代碼的可讀性、可維護(hù)性和可擴(kuò)展性。選擇適當(dāng)?shù)脑O(shè)計(jì)模式可以使開(kāi)發(fā)過(guò)程更高效,減少錯(cuò)誤,并降低系統(tǒng)復(fù)雜性。然而,要根據(jù)具體問(wèn)題和需求來(lái)選擇和實(shí)現(xiàn)設(shè)計(jì)模式,而不是機(jī)械地應(yīng)用它們。在實(shí)際開(kāi)發(fā)中,理解設(shè)計(jì)模式的核心概念和原則將成為更出色的軟件工程師。