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
其他設計模式介紹
-
享元模式(Flyweight Pattern):運用共享技術有效地支持大量細粒度的對象。
-
代理模式(Proxy Pattern):爲其他對象提供一種代理以控制對這個對象的訪問。
-
責任鏈模式(Chain of Responsibility Pattern):爲解除請求的發送者和接收者之間耦合,而使多個對象都有機會處理這個請求,將這些對象連成一條鏈,並沿着這條鏈傳遞請求,直到有一個對象處理它爲止。
-
命令模式(Command Pattern):將一個請求封裝爲一個對象,從而使你可以用不同的請求對客戶進行參數化。
-
解釋器模式(Interpreter Pattern):給定一個語言,定義它的文法的一種表示,並定義一個解釋器,這個解釋器使用該表示來解釋語言中的句子
-
迭代器模式(Iterator Pattern):提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。
-
中介者模式(Mediator Pattern):用一箇中介對象來封裝一系列的對象交互。
-
備忘錄模式(Memento Pattern):在不破壞封裝性的前提下,捕獲一個對象的內部狀態,並在該對象之外保存這個狀態。
-
觀察者模式(Observer Pattern):定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並自動刷新。
-
狀態模式(State Pattern):允許一個對象在其內部狀態改變時改變它的行爲。
-
策略模式(Strategy Pattern):定義一系列算法,將每個算法都封裝起來,並使它們之間可以互換。
-
模板方法模式(Template Method Pattern):定義一個操作中的算法的骨架,而將一些步驟延遲到子類中。
-
訪問者模式(Visitor Pattern):封裝一些作用於某種數據結構中的各元素的操作,它可以在不改變數據結構的前提下定義作用於這些元素的新的操作。
來源:
https://www.toutiao.com/article/7231418050682307083/?log_from=8ba2847ed493e_1683767319086
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/kjL5YkoN2z380TMD6gkgKA