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):封裝一些作用于某種資料結構中的各元素的操作,它可以在不改變資料結構的前提下定義作用于這些元素的新的操作。