IT 領域中最常見的 23 種設計模式

當應用程序變得複雜時,使用設計模式可以幫助我們更好地組織和管理代碼。設計模式是一種被廣泛接受的解決問題的方法,它們提供了一個經過實踐驗證的框架,可以被用於各種不同的應用程序和情境。

在 IT 領域中,最常見的 23 種設計模式是由 Gang of Four(四人組)所定義的。這些模式可以分爲三類:創建型模式(Creational Patterns)、結構型模式(Structural Patterns)和行爲型模式(Behavioral Patterns)。

創建型模式關注對象的創建過程,它們包括工廠方法模式、抽象工廠模式、單例模式、建造者模式和原型模式。

結構型模式關注對象和類的組合關係,它們包括適配器模式、橋接模式、組合模式、裝飾器模式、外觀模式、享元模式和代理模式。

行爲型模式關注對象之間的通信和協作,它們包括模板方法模式、策略模式、命令模式、職責鏈模式、狀態模式、觀察者模式、中介者模式和訪問者模式。

每種設計模式都有其獨特的用途和優點,可以根據具體的情況來選擇使用。在編寫代碼時,使用設計模式可以使代碼更加靈活、可維護和可擴展,從而提高代碼的質量和可重用性。

接下來我將介紹常用的幾個設計模式及其代碼示例。

工廠方法模式(Factory Method Pattern)

定義一個用於創建對象的接口,讓子類決定實例化哪一個類。

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "汪汪"

class Cat(Animal):
    def sound(self):
        return "喵喵"

class AnimalFactory(ABC):
    @abstractmethod
    def create_animal(self):
        pass

class DogFactory(AnimalFactory):
    def create_animal(self):
        return Dog()

class CatFactory(AnimalFactory):
    def create_animal(self):
        return Cat()

dog_factory = DogFactory()
dog = dog_factory.create_animal()
print(dog.sound())  # 輸出:汪汪

cat_factory = CatFactory()
cat = cat_factory.create_animal()
print(cat.sound())  # 輸出:喵喵

抽象工廠模式(Abstract Factory Pattern)

提供一個創建一系列相關或相互依賴對象的接口,而無需指定它們具體的類。

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "汪汪"

class Cat(Animal):
    def sound(self):
        return "喵喵"

class Food(ABC):
    @abstractmethod
    def taste(self):
        pass

class Bone(Food):
    def taste(self):
        return "骨頭味"

class Fish(Food):
    def taste(self):
        return "魚味"

class AnimalFactory(ABC):
    @abstractmethod
    def create_animal(self):
        pass

class FoodFactory(ABC):
    @abstractmethod
    def create_food(self):
        pass

class DogFactory(AnimalFactory, FoodFactory):
    def create_animal(self):
        return Dog()

    def create_food(self):
        return Bone()

class CatFactory(AnimalFactory, FoodFactory):
    def create_animal(self):
        return Cat()

    def create_food(self):
        return Fish()

dog_factory = DogFactory()
dog = dog_factory.create_animal()
food = dog_factory.create_food()
print(dog.sound())   # 輸出:汪汪
print(food.taste())  # 輸出:骨頭味

cat_factory = CatFactory()
cat = cat_factory.create_animal()
food = cat_factory.create_food()
print(cat.sound())   # 輸出:喵喵
print(food.taste())  # 輸出:魚味

單例模式(Singleton Pattern):確保一個類只有一個實例,並提供全局訪問點。

class Singleton:
    __instance = None

    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

obj1 = Singleton()
obj2 = Singleton()

print(obj1 is obj2)  # 輸出:True

建造者模式(Builder Pattern):將一個複雜對象的構建與其表示相分離,使得同樣的構建過程可以創建不同的表示。

class Computer:
    def __init__(self, cpu=None, memory=None, storage=None):
        self.cpu = cpu
        self.memory = memory
        self.storage = storage

class ComputerBuilder:
    def __init__(self):
        self.computer = Computer()

    def set_cpu(self, cpu):
        self.computer.cpu = cpu

    def set_memory(self, memory):
        self.computer.memory = memory

    def set_storage(self, storage):
        self.computer.storage = storage

    def build(self):
        return self.computer

builder = ComputerBuilder()
builder.set_cpu("Intel Core i7")
builder.set_memory("16GB")
builder.set_storage("512GB SSD")

computer = builder.build()

print(computer.cpu)      # 輸出:Intel Core i7
print(computer.memory)   # 輸出:16GB
print(computer.storage)  # 輸出:512GB SSD

原型模式(Prototype Pattern):用原型實例指定創建對象的種類,並通過複製這些原型創建新的對象。

import copy

class Prototype:
    def __init__(self):
        self.name = "default"

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

class ConcretePrototypeA(Prototype):
    def __init__(self):
        super().__init__()
        self.name = "A"

class ConcretePrototypeB(Prototype):
    def __init__(self):
        super().__init__()
        self.name = "B"

prototype_a = ConcretePrototypeA()
clone_a = prototype_a.clone()
print(clone_a.name)  # 輸出:A

prototype_b = ConcretePrototypeB()
clone_b = prototype_b.clone()
print(clone_b.name)  # 輸出:B

適配器模式(Adapter Pattern):將一個類的接口轉換成客戶希望的另外一個接口。

class Target:
    def request(self):
        return "Target request"

class Adaptee:
    def specific_request(self):
        return "Adaptee request"

class Adapter(Target):
    def __init__(self, adaptee):
        self.adaptee = adaptee

    def request(self):
        return f"Adapter request: {self.adaptee.specific_request()}"

adaptee = Adaptee()
adapter = Adapter(adaptee)

print(adapter.request())  # 輸出:Adapter request: Adaptee request

橋接模式(Bridge Pattern):將抽象部分與它的實現部分分離,使它們都可以獨立地變化。

from abc import ABC, abstractmethod

class Implementor(ABC):
    @abstractmethod
    def operation(self):
        pass

class ConcreteImplementorA(Implementor):
    def operation(self):
        return "ConcreteImplementorA operation"

class ConcreteImplementorB(Implementor):
    def operation(self):
        return "ConcreteImplementorB operation"

class Abstraction:
    def __init__(self, implementor):
        self.implementor = implementor

    def operation(self):
        return f"Abstraction: {self.implementor.operation()}"

implementor_a = ConcreteImplementorA()
abstraction = Abstraction(implementor_a)
print(abstraction.operation())  # 輸出:Abstraction: ConcreteImplementorA operation

implementor_b = ConcreteImplementorB()
abstraction = Abstraction(implementor_b)
print(abstraction.operation())  # 輸出:Abstraction: ConcreteImplementorB operation

組合模式(Composite Pattern):將對象組合成樹形結構以表示 “部分 - 整體” 的層次結構。

from abc import ABC, abstractmethod

class Component(ABC):
    @abstractmethod
    def operation(self):
        pass

class Leaf(Component):
    def operation(self):
        return "Leaf operation"

class Composite(Component):
    def __init__(self):
        self.children = []

    def add(self, component):
        self.children.append(component)

    def remove(self, component):
        self.children.remove(component)

    def operation(self):
        results = []
        for child in self.children:
            results.append(child.operation())
        return f"Composite operation: [{', '.join(results)}]"

leaf = Leaf()
print(leaf.operation())  # 輸出:Leaf operation

composite = Composite()
composite.add(Leaf())
composite.add(Leaf())
print(composite.operation())  # 輸出:Composite operation: [Leaf operation, Leaf operation]

裝飾器模式(Decorator Pattern):動態地給一個對象添加一些額外的職責。

from abc import ABC, abstractmethod

class Component(ABC):
    @abstractmethod
    def operation(self):
        pass

class ConcreteComponent(Component):
    def operation(self):
        return "ConcreteComponent operation"

class Decorator(Component):
    def __init__(self, component):
        self.component = component

    def operation(self):
        return f"Decorator operation: {self.component.operation()}"

component = ConcreteComponent()
decorator = Decorator(component)
print(decorator.operation())  # 輸出:Decorator operation: ConcreteComponent operation

外觀模式(Facade Pattern):爲子系統中的一組接口提供一個一致的界面,定義一個高層接口,使得這個子系統更加易於使用。

class SubsystemA:
    def operation_a(self):
        return "SubsystemA operation"

class SubsystemB:
    def operation_b(self):
        return "SubsystemB operation"

class Facade:
    def __init__(self):
        self.subsystem_a = SubsystemA()
        self.sub

其他設計模式介紹

來源:

https://www.toutiao.com/article/7231418050682307083/?log_from=8ba2847ed493e_1683767319086

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/kjL5YkoN2z380TMD6gkgKA