成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Python的設計模式:構建更優雅的代碼

開發 后端
Python的設計模式是一種有關如何解決特定問題或設計靈活可維護代碼的指導原則。設計模式是開發者們多年經驗的總結,可以在面對各種軟件設計挑戰時提供有力的解決方案。

設計模式是在軟件工程中廣泛使用的經驗豐富的解決問題的方法。它們是通用的、可重復使用的解決方案,用于解決常見的設計問題。設計模式有助于使代碼更易于理解、可維護和可擴展。Python作為一門多范式的編程語言,提供了豐富的設計模式應用場景。

在本文中,我們將詳細介紹 Python 中的各種設計模式,包括創建型、結構型和行為型模式。

創建型模式

創建型模式關注對象的創建機制,它們包括單例、工廠、抽象工廠、建造者和原型模式。這些模式旨在提供一種靈活的方式來創建對象,同時減少對象創建的復雜性。

單例模式

單例模式確保一個類只有一個實例,并提供一個全局訪問點。這對于需要在應用程序中共享資源的情況非常有用,例如配置管理、日志記錄和數據庫連接。

示例代碼:

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

單例模式確保只創建一個實例,即使多次創建也返回相同的實例。

工廠模式

工廠模式用于創建對象,將對象的創建邏輯封裝在一個方法中,從而實現對象的創建和使用的解耦。工廠模式可以根據傳入的參數選擇創建哪種類型的對象。

示例代碼:

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")

工廠模式將對象創建的邏輯封裝在一個工廠類中,客戶端可以根據需要創建不同類型的對象。

抽象工廠模式

抽象工廠模式提供了一種創建相關對象家族的方式,而無需指定它們的具體類。這允許創建一組相關對象,例如不同操作系統下的窗口和按鈕。

示例代碼:

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

抽象工廠模式創建一組相關的對象,例如在不同操作系統下使用不同樣式的界面組件。

建造者模式

建造者模式將一個復雜對象的構建過程分解為一系列步驟,使客戶端能夠按步驟構建對象。這對于構建包含許多可選組件的對象非常有用。

示例代碼:

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()

建造者模式逐步構建一個對象,設置其屬性并最終構建對象。這對于構建參數眾多的對象非常有用。

原型模式

原型模式通過復制現有對象來創建新對象。這對于創建大型對象或需要定制初始化的對象非常有用。原型模式可以克隆一個現有對象,而無需從頭創建一個新對象。

示例代碼:

import copy

class Prototype:
    def __init__(self):
        self.items = []

    def clone(self):
        return copy.deepcopy(self)

# 使用原型模式
original = Prototype()
original.items.append("item1")

# 克隆原型對象
clone = original.clone()
clone.items.append("item2")

print(original.items)  # 輸出:['item1']
print(clone.items)     # 輸出:['item1', 'item2']

原型模式可以克隆對象,能夠在不從頭創建對象的情況下生成新對象。

結構型模式

結構型模式處理對象之間的關系,包括適配器、橋接、組合、裝飾器、外觀、享元和代理模式。這些模式有助于定義對象之間的協作方式,同時保持系統的靈活性和可維護性。

適配器模式

適配器模式用于將一個接口轉換成另一個接口,以使不兼容的類可以一起工作。適配器模式使用不同接口的對象協同工作。

示例代碼:

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

適配器模式允許新舊系統一起工作,將新系統的接口適配為舊系統可以使用的接口。

橋接模式

橋接模式將抽象部分與實現部分分離,它們可以獨立變化。這有助于減少類之間的耦合,同時允許它們在運行時獨立變化。

示例代碼:

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分開,使它們可以獨立變化。這有助于降低系統的復雜性。

組合模式

組合模式用于將對象組織成樹狀結構,以表示部分-整體關系。這使得客戶端可以統一處理單個對象和組合對象,從而簡化代碼。

示例代碼:

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]

組合模式允許構建包含子組件的復雜對象,同時使客戶端能夠一致地處理單個對象和組合對象。

裝飾器模式

裝飾器模式動態地將責任附加到對象上。它是在不修改對象源代碼的情況下擴展對象功能的一種方式。

示例代碼:

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

裝飾器模式在運行時動態地添加新功能或修改對象的行為。

外觀模式

外觀模式提供了一個統一的接口,用于訪問子系統中的一組接口。這簡化了復雜子系統的使用,為客戶端提供了一個簡化的接口。

示例代碼:

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)

外觀模式提供了一個高級接口,使客戶端能夠訪問一組子系統接口,而不必了解其復雜性。

享元模式

享元模式用于共享大量細粒度對象,以減少內存占用。它將對象的共享部分抽象出來,以減少對象的數量。

示例代碼:

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

享元模式允許多個對象共享相同的內部狀態,從而降低內存占用。

代理模式

代理模式允許創建一個代理對象,用于控制對其他對象的訪問。代理對象充當被代理對象的接口,以便在不直接訪問被代理對象的情況下執行其他操作。

示例代碼:

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

代理模式允許代理對象控制對真實對象的訪問,從而提供附加的功能或控制。

行為型模式

行為型模式處理對象之間的通信,包括觀察者、策略、命令、責任鏈、狀態、訪問者、迭代器、備忘錄、中介者、解釋器和模板方法模式。這些模式有助于定義對象之間的交互和職責分配。

觀察者模式

觀察者模式定義了一種一對多的依賴關系,其中一個對象的狀態發生變化時,其所有依賴對象都會得到通知。

示例代碼:

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

觀察者模式允許主題對象和觀察者對象之間保持松散的耦合,主題對象的狀態變化會自動通知觀察者對象。

策略模式

策略模式定義了一系列算法,封裝每個算法,并使它們可以相互替換。這提供了靈活性,允許在運行時選擇算法。

示例代碼:

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

策略模式允許定義一組算法,并將它們封裝在可互換的策略對象中,以便在運行時選擇不同的算法。

命令模式

命令模式將請求封裝成一個對象,從而可以參數化客戶端對象操作,隊列請求或記錄請求日志。

示例代碼:

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

命令模式將請求和處理請求的對象解耦,允許將命令存儲、排隊和操作。

責任鏈模式

責任鏈模式構建一系列對象,每個對象負責處理請求的一部分。請求按順序通過鏈傳遞,直到有一個對象處理它為止。

示例代碼:

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"

# 使用責任鏈模式
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

責任鏈模式允許構建對象鏈,其中每個對象決定是否處理請求或將其傳遞給下一個對象。

狀態模式

狀態模式允許對象在其內部狀態改變時改變其行為。這將狀態轉移邏輯封裝在不同的狀態類中。

示例代碼:

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()

# 使用狀態模式
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

狀態模式允許對象在其內部狀態改變時改變其行為,從而使其看起來像是更改了類。

訪問者模式

訪問者模式允許在不修改對象結構的情況下為對象結構中的元素添加新操作。它通過將訪問操作從元素類中分離出來來實現這一點。

示例代碼:

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__}"

# 使用訪問者模式
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

訪問者模式將元素和訪問操作分離,為元素添加新操作而無需修改元素類。

迭代器模式

迭代器模式在不暴露集合的內部表示的情況下順序訪問集合的元素。

示例代碼:

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

迭代器模式順序訪問集合的元素,而無需暴露其內部表示。

備忘錄模式

備忘錄模式用于捕獲一個對象的內部狀態,以便以后可以將其恢復到該狀態。它將對象狀態的保存和恢復分離開來。

示例代碼:

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

備忘錄模式保存對象的狀態,并在需要時將其恢復到以前的狀態。

中介者模式

中介者模式用于減少對象之間的直接通信,將對象之間的交互集中到中介者對象中。這有助于減少對象之間的耦合。

示例代碼:

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")

中介者模式將對象之間的通信集中到中介者對象中,減少了對象之間的直接耦合。

解釋器模式

解釋器模式用于定義一門語言的語法,以解釋語言中的句子。它將語法規則和解釋邏輯分開。

示例代碼:

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

解釋器模式定義一門語言的語法,并為語言中的句子創建解釋器。

模板方法模式

模板方法模式定義了一個算法的骨架,將算法的一些步驟推遲到子類中。這允許子類在不改變算法結構的情況下重新定義算法的某些步驟。

示例代碼:

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

模板方法模式定義了一個算法的骨架,允許子類提供實現特定步驟的方法。

結論

Python的設計模式是一種有關如何解決特定問題或設計靈活可維護代碼的指導原則。設計模式是開發者們多年經驗的總結,可以在面對各種軟件設計挑戰時提供有力的解決方案。

創建型設計模式處理對象的創建,包括單例、工廠、抽象工廠、建造者和原型模式。這些模式可以靈活地管理對象的生命周期和創建過程。

結構型設計模式有助于組織和管理對象之間的關系,包括適配器、裝飾器、代理、組合、橋接、享元和外觀模式。它們構建更靈活和可維護的系統。

行為型設計模式處理對象之間的通信和協作,包括觀察者、策略、命令、責任鏈、狀態、訪問者、迭代器、備忘錄、中介者、解釋器和模板方法模式。這些模式有助于定義對象之間的交互和協作方式。

設計模式可以提高代碼的可讀性、可維護性和可擴展性。選擇適當的設計模式可以使開發過程更高效,減少錯誤,并降低系統復雜性。然而,要根據具體問題和需求來選擇和實現設計模式,而不是機械地應用它們。在實際開發中,理解設計模式的核心概念和原則將成為更出色的軟件工程師。

責任編輯:姜華 來源: 今日頭條
相關推薦

2025-02-12 08:04:54

代碼Ordersetter

2022-05-13 08:48:50

React組件TypeScrip

2023-12-21 10:26:30

??Prettier

2020-04-03 14:55:39

Python 代碼編程

2022-03-11 12:14:43

CSS代碼前端

2022-03-08 06:41:35

css代碼

2025-02-10 00:25:00

命令模式擴展機制系統

2023-11-02 09:02:55

Java模式

2023-11-23 13:50:00

Python代碼

2021-12-13 14:37:37

React組件前端

2024-01-23 11:21:24

2022-04-10 10:41:17

ESLint異步代碼

2021-12-07 08:16:34

React 前端 組件

2019-09-29 16:17:25

Java代碼性能編程語言

2018-07-12 14:20:33

SQLSQL查詢編寫

2021-12-29 17:24:16

Kubernetes集群事件

2021-06-25 15:53:25

Kubernetes程序技巧

2024-07-30 14:09:19

裝飾器Python代碼

2022-09-27 15:34:05

VSCode插件開發

2022-07-03 10:23:06

機器人場景個性化
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 午夜午夜精品一区二区三区文 | 久久久久久久夜 | 在线观看亚洲欧美 | 色偷偷噜噜噜亚洲男人 | 乱码av午夜噜噜噜噜动漫 | 久色网| 国产激情视频在线观看 | jvid精品资源在线观看 | 99国产精品一区二区三区 | 天堂va在线| 成人小视频在线观看 | 天天影视网天天综合色在线播放 | 一区二区三区精品视频 | 亚洲高清在线 | 中文字幕一区二区三区四区五区 | 免费在线观看91 | 色www精品视频在线观看 | 天天天天天天天干 | 久久久久一区 | 国产精品1区2区3区 中文字幕一区二区三区四区 | 久久伊人精品 | 国产自产21区 | av特级毛片 | 国产aaaaav久久久一区二区 | 免费看黄色视屏 | 一级黄色片日本 | 欧美理论片在线观看 | www国产成人免费观看视频,深夜成人网 | 国产精品亚洲一区 | 精品一二三区 | 成人国产a | 男女污污动态图 | 日本天天操| 精品一区二区三区在线观看国产 | 久久国产成人 | 国产福利在线免费观看 | 日韩在线资源 | 91福利在线观看 | 亚洲欧美一区二区三区在线 | 精品一二 | 一区二区三区国产在线观看 |