狂自私

导航

常见设计模式

设计模式是一种在软件开发中常用的解决特定问题的通用方法。它们提供了一种标准化的方式来构建和组织代码,提高代码的可重用性和可维护性。以下是一些常见的设计模式,通常可以分为三大类:创建型、结构型和行为型。

1. 创建型模式

这些模式主要关注对象的创建过程。

  • 单例模式(Singleton)
    确保一个类只有一个实例,并提供一个全局访问点。适用于需要控制资源访问的场景,如配置管理。

    class Singleton:
        _instance = None
    
        def __new__(cls):
            if cls._instance is None:
                cls._instance = super(Singleton, cls).__new__(cls)
            return cls._instance
    
  • 工厂模式(Factory)
    定义一个接口用于创建对象,但由子类决定要实例化的类。常用于需要动态选择某种类型对象的情况。

    class Shape:
        def draw(self):
            pass
    
    class Circle(Shape):
        def draw(self):
            print("Draw a Circle")
    
    class ShapeFactory:
        @staticmethod
        def get_shape(shape_type):
            if shape_type == "Circle":
                return Circle()
    
  • 抽象工厂模式(Abstract Factory)
    提供一个接口,用于创建一系列相关或相互依赖的对象,而无需指定它们的具体类。

2. 结构型模式

这些模式主要关注对象之间的组合。

  • 适配器模式(Adapter)
    将一个类的接口转换为客户端所期望的另一个接口。适用于需要使用现有类而其接口不兼容的情况。

    class Adaptee:
        def specific_request(self):
            return "Specific Request"
    
    class Adapter:
        def __init__(self, adaptee):
            self.adaptee = adaptee
    
        def request(self):
            return self.adaptee.specific_request()
    
  • 装饰者模式(Decorator)
    动态地给一个对象添加一些额外的职责。适用于需要扩展类功能的情况。

    class Coffee:
        def cost(self):
            return 5
    
    class MilkDecorator:
        def __init__(self, coffee):
            self.coffee = coffee
    
        def cost(self):
            return self.coffee.cost() + 1
    
  • 组合模式(Composite)
    将对象组合成树形结构以表示“部分-整体”层次结构。客户对单个对象和组合对象的使用保持一致。

3. 行为型模式

这些模式主要关注对象之间的通信。

  • 观察者模式(Observer)
    定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象发生变化时,所有依赖于它的观察者都会收到通知。

    class Subject:
        def __init__(self):
            self.observers = []
    
        def attach(self, observer):
            self.observers.append(observer)
    
        def notify(self):
            for observer in self.observers:
                observer.update()
    
  • 策略模式(Strategy)
    定义一系列算法,将每一个算法封装起来,并使它们可以互换。适用于需要在运行时选择算法的情况。

    class Strategy:
        def execute(self):
            pass
    
    class ConcreteStrategyA(Strategy):
        def execute(self):
            print("Strategy A")
    
    class Context:
        def __init__(self, strategy):
            self.strategy = strategy
    
        def execute_strategy(self):
            self.strategy.execute()
    
  • 命令模式(Command)
    将请求封装为对象,以便使用不同的请求、队列或日志请求,以及支持可撤销操作。

总结

设计模式在软件开发中具有重要意义,它们提供了可重用的解决方案,帮助开发者解决常见问题。尽管学习和应用设计模式可能需要一定的时间和经验,但掌握它们将显著提升代码的质量和可维护性。

posted on 2024-09-12 09:08  狂自私  阅读(25)  评论(0)    收藏  举报