欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python設(shè)計模式優(yōu)雅構(gòu)建代碼全面教程示例

 更新時間:2023年11月30日 09:03:12   作者:濤哥聊Python  
Python作為一門多范式的編程語言,提供了豐富的設(shè)計模式應(yīng)用場景,在本文中,我們將詳細介紹 Python 中的各種設(shè)計模式,包括創(chuàng)建型、結(jié)構(gòu)型和行為型模式

引言

設(shè)計模式是在軟件工程中廣泛使用的經(jīng)驗豐富的解決問題的方法。它們是通用的、可重復(fù)使用的解決方案,用于解決常見的設(shè)計問題。設(shè)計模式有助于使代碼更易于理解、可維護和可擴展。

創(chuàng)建型模式

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

單例模式

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

示例代碼:

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)建一個實例,即使多次創(chuàng)建也返回相同的實例。

工廠模式

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

示例代碼:

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

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

抽象工廠模式

抽象工廠模式提供了一種創(chuàng)建相關(guān)對象家族的方式,而無需指定它們的具體類。這允許創(chuàng)建一組相關(guān)對象,例如不同操作系統(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)的對象,例如在不同操作系統(tǒng)下使用不同樣式的界面組件。

建造者模式

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

示例代碼:

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)建一個對象,設(shè)置其屬性并最終構(gòu)建對象。這對于構(gòu)建參數(shù)眾多的對象非常有用。

原型模式

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

示例代碼:

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']

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

結(jié)構(gòu)型模式

結(jié)構(gòu)型模式處理對象之間的關(guān)系,包括適配器、橋接、組合、裝飾器、外觀、享元和代理模式。這些模式有助于定義對象之間的協(xié)作方式,同時保持系統(tǒng)的靈活性和可維護性。

適配器模式

適配器模式用于將一個接口轉(zhuǎn)換成另一個接口,以使不兼容的類可以一起工作。適配器模式使用不同接口的對象協(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)可以使用的接口。

橋接模式

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

示例代碼:

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

組合模式

組合模式用于將對象組織成樹狀結(jié)構(gòu),以表示部分-整體關(guān)系。這使得客戶端可以統(tǒng)一處理單個對象和組合對象,從而簡化代碼。

示例代碼:

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ù)雜對象,同時使客戶端能夠一致地處理單個對象和組合對象。

裝飾器模式

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

示例代碼:

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

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

外觀模式

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

示例代碼:

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)

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

享元模式

享元模式用于共享大量細粒度對象,以減少內(nèi)存占用。它將對象的共享部分抽象出來,以減少對象的數(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

享元模式允許多個對象共享相同的內(nèi)部狀態(tài),從而降低內(nèi)存占用。

代理模式

代理模式允許創(chuàng)建一個代理對象,用于控制對其他對象的訪問。代理對象充當被代理對象的接口,以便在不直接訪問被代理對象的情況下執(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

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

行為型模式

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

觀察者模式

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

示例代碼:

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

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

策略模式

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

示例代碼:

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

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

命令模式

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

示例代碼:

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

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

責任鏈模式

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

示例代碼:

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

責任鏈模式允許構(gòu)建對象鏈,其中每個對象決定是否處理請求或?qū)⑵鋫鬟f給下一個對象。

狀態(tài)模式

狀態(tài)模式允許對象在其內(nèi)部狀態(tài)改變時改變其行為。這將狀態(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)模式允許對象在其內(nèi)部狀態(tài)改變時改變其行為,從而使其看起來像是更改了類。

訪問者模式

訪問者模式允許在不修改對象結(jié)構(gòu)的情況下為對象結(jié)構(gòu)中的元素添加新操作。它通過將訪問操作從元素類中分離出來來實現(xià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__}"
# 使用訪問者模式
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

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

迭代器模式

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

示例代碼:

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

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

備忘錄模式

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

示例代碼:

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

備忘錄模式保存對象的狀態(tài),并在需要時將其恢復(fù)到以前的狀態(tài)。

中介者模式

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

示例代碼:

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

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

解釋器模式

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

示例代碼:

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

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

模板方法模式

模板方法模式定義了一個算法的骨架,將算法的一些步驟推遲到子類中。這允許子類在不改變算法結(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

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

總結(jié)

Python的設(shè)計模式是一種有關(guān)如何解決特定問題或設(shè)計靈活可維護代碼的指導(dǎo)原則。設(shè)計模式是開發(fā)者們多年經(jīng)驗的總結(jié),可以在面對各種軟件設(shè)計挑戰(zhàn)時提供有力的解決方案。

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

結(jié)構(gòu)型設(shè)計模式有助于組織和管理對象之間的關(guān)系,包括適配器、裝飾器、代理、組合、橋接、享元和外觀模式。它們構(gòu)建更靈活和可維護的系統(tǒng)。

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

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

以上就是Python設(shè)計模式優(yōu)雅構(gòu)建代碼全面教程示例的詳細內(nèi)容,更多關(guān)于Python設(shè)計模式的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python基礎(chǔ)入門之seed()方法的使用

    Python基礎(chǔ)入門之seed()方法的使用

    這篇文章主要介紹了Python基礎(chǔ)入門之seed()方法的使用,是Python學習當中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-05-05
  • Python實現(xiàn)AES加密,解密的兩種方法

    Python實現(xiàn)AES加密,解密的兩種方法

    這篇文章主要介紹了Python實現(xiàn)AES加密,解密的兩種方法,幫助大家更好的使用python加解密文件,感興趣的朋友可以了解下
    2020-10-10
  • Pytest自動化測試的具體使用

    Pytest自動化測試的具體使用

    Pytest是一個Python的自動化測試框架,它可用于編寫單元測試、功能測試、集成測試和端到端測試,本文就來介紹一下Pytest自動化測試的具體使用,感興趣的可以了解一下
    2024-01-01
  • python實現(xiàn)京東秒殺功能

    python實現(xiàn)京東秒殺功能

    這篇文章主要為大家詳細介紹了python實現(xiàn)京東秒殺功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python實現(xiàn)調(diào)度算法代碼詳解

    Python實現(xiàn)調(diào)度算法代碼詳解

    這篇文章主要介紹了Python實現(xiàn)調(diào)度場算法代碼詳解,具有一定參考價值,需要的朋友可以了解下。
    2017-12-12
  • PyPy?如何讓Python代碼運行得和C一樣快

    PyPy?如何讓Python代碼運行得和C一樣快

    這篇文章主要介紹了如何讓Python代碼運行得和C一樣快,由于?PyPy?只是?Python?的一種替代實現(xiàn),大多數(shù)時候它都是開箱即用,無需對?Python?項目進行任何更改。它與?Web?框架?Django、科學計算包?Numpy?和許多其他包完全兼容,推薦大家多多使用
    2022-01-01
  • 深入理解Django-Signals信號量

    深入理解Django-Signals信號量

    這篇文章主要介紹了深入理解Django-Signals信號量,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • 對Python獲取屏幕截圖的4種方法詳解

    對Python獲取屏幕截圖的4種方法詳解

    今天小編就為大家分享一篇對Python獲取屏幕截圖的4種方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Django框架基礎(chǔ)模板標簽與filter使用方法詳解

    Django框架基礎(chǔ)模板標簽與filter使用方法詳解

    這篇文章主要介紹了Django框架基礎(chǔ)模板標簽與filter使用方法,簡單分析了Django模板基本語法、函數(shù)與自定義filter相關(guān)使用技巧,需要的朋友可以參考下
    2019-07-07
  • k-means 聚類算法與Python實現(xiàn)代碼

    k-means 聚類算法與Python實現(xiàn)代碼

    這篇文章主要介紹了k-means 聚類算法與Python實現(xiàn)代碼,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06

最新評論