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):封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。