【Python进阶编程】python编程高手常用的设计模式(持续更新中)

news/2024/6/18 22:25:30 标签: python, 开发语言

Python编程高手通常熟练运用各种设计模式,这些设计模式有助于提高代码的可维护性、可扩展性和重用性。

以下是一些Python编程高手常用的设计模式:

1.单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供全局访问点。适用于需要共享资源或控制特定资源访问的情景。

python">class Singleton(object):
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance


s1 = Singleton()
s2 = Singleton()
print(id(s1))
print(id(s2)) # s1和s2的ID应该是一样的,表明这是同一个对象

其他实现单例模式的方法。

1.1 使用模块级别的变量实现单例模式

python"># singleton_module.py

class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

singleton_instance = Singleton()

Python模块在程序中只会被导入一次,因此模块级别的变量可以实现单例模式。

在其他文件中,可以通过导入singleton_module模块来获取单例对象:

python"># main.py

from singleton_module import singleton_instance

# 使用单例对象
singleton_instance.set_value(42)
print(singleton_instance.get_value())

1.2 使用类装饰器实现单例模式

可以使用装饰器来确保类只有一个实例,并通过装饰器在需要时创建实例。

python"># singleton_decorator.py

def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

在这种方式下,可以直接使用@singleton装饰器标记一个类为单例,然后通过类的实例获取单例对象:

python"># main.py

from singleton_decorator import Singleton

# 使用单例对象
singleton_instance = Singleton()
singleton_instance.set_value(42)
print(singleton_instance.get_value())



2. 工厂模式(Factory Pattern)

  1.  定义一个接口,但由子类决定实例化哪个类。工厂方法模式将类的实例化延迟到子类。

    python">
    class Product(ABC):
        @abstractmethod
        def create_product(self):
            pass
    
    class ConcreteProductA(Product):
        def create_product(self):
            return "Product A"
    
    class ConcreteProductB(Product):
        def create_product(self):
            return "Product B"

    3.观察者模式(Observer Pattern)

python">from abc import ABC, abstractmethod

class Observer(ABC):
    @abstractmethod
    def update(self, message):
        pass

class ConcreteObserver(Observer):
    def update(self, message):
        print(f"Received message: {message}")

class Subject:
    _observers = []

    def add_observer(self, observer):
        self._observers.append(observer)

    def remove_observer(self, observer):
        self._observers.remove(observer)

    def notify_observers(self, message):
        for observer in self._observers:
            observer.update(message)


​​​​​​4. 策略模式(Strategy Pattern)

  1. 定义一系列算法,将每个算法封装起来,并使它们可以互换。策略模式可以使算法独立于客户端而变化。

    python">from abc import ABC, abstractmethod
    
    class Strategy(ABC):
        @abstractmethod
        def execute(self):
            pass
    
    class ConcreteStrategyA(Strategy):
        def execute(self):
            return "Strategy A"
    
    class ConcreteStrategyB(Strategy):
        def execute(self):
            return "Strategy B"
    
    class Context:
        def __init__(self, strategy):
            self._strategy = strategy
    
        def execute_strategy(self):
            return self._strategy.execute()

5.装饰器模式(Decorator Pattern)

  1.  动态地给一个对象添加一些额外的职责,装饰模式比继承更加灵活。

     
    python">from abc import ABC, abstractmethod
    
    class Component(ABC):
        @abstractmethod
        def operation(self):
            pass
    
    class ConcreteComponent(Component):
        def operation(self):
            return "Concrete Component"
    
    class Decorator(Component):
        _component = None
    
        def __init__(self, component):
            self._component = component
    
        def operation(self):
            return self._component.operation()
    
    class ConcreteDecorator(Decorator):
        def operation(self):
            return f"{super().operation()}, Decorated"


http://www.niftyadmin.cn/n/5342714.html

相关文章

Spring第一天

学习目标 能够说出Spring的体系结构 能够编写IOC入门案例 能够编写DI入门案例 能够配置setter方式注入属性值 能够配置构造方式注入属性值 能够理解什么是自动装配 一、Spring简介 1 Spring课程介绍 问题导入 我们为什么要学习Spring框架? 1.1 为什么要学 Spri…

一个处理Range List的面试题解法

大纲 题目解法Rangeaddremove ToolsRangeListaddremove 代码 最近看到一个比较有意思的面试题。题目不算难,但是想把效率优化做好,也没那么容易。 我们先看下题目 题目 // Task: Implement a class named RangeList // A pair of integers define a ra…

java 开源中文的繁简体转换工具 opencc4j

Opencc4j Opencc4j 支持中文繁简体转换,考虑到词组级别。 Features 特点 严格区分「一简对多繁」和「一简对多异」。 完全兼容异体字,可以实现动态替换。 严格审校一简对多繁词条,原则为「能分则不合」。 词库和函数库完全分离&#xff…

LeetCode第303题 - 区域和检索 - 数组不可变

题目 解答 方案一:直观的实现。 class NumArray {private int[] nums;public NumArray(int[] nums) {if (nums ! null) {this.nums new int[nums.length];System.arraycopy(nums, 0, this.nums, 0, nums.length);}}public int sumRange(int i, int j) {int sum …

Linux环境docker安装Neo4j,以及Neo4j新手入门教学(超详细版本)

目录 1、 图数据库Neo4j简介1.1 什么是图数据库1.2 能解决什么痛点1.3 对比关系型数据库1.4 什么是Neo4j1.5 Neo4j的构建元素 2. 环境搭建2.1 安装Neo4j Community Server2.2 docker 安装Neo4j Community Server2.3 Neo4j Desktop安装 3. Neo4j - CQL使用3.1 Neo4j - CQL简介3.…

springboot中redis的配置详细讲解

在Spring Boot中配置Redis主要涉及以下几个方面&#xff1a;引入依赖、配置连接信息、配置连接池、配置操作模板。 引入依赖&#xff1a;首先&#xff0c;在项目的pom.xml文件中添加Redis相关的依赖&#xff0c;例如&#xff1a; <dependency><groupId>org.sprin…

c#中使用UTF-8编码处理多语言文本的有效策略

使用UTF-8编码处理多语言文本的有效策略 在当今的全球化时代&#xff0c;软件开发者常常需要处理包含多种语言的文本。这不仅涉及英文和其他西方语言&#xff0c;还包括中文、日文、韩文等多字节字符系统。在这篇博客中&#xff0c;我将探讨如何有效地使用UTF-8编码来处理混合语…

E - Souvenir(图论典型例题)

思路&#xff1a;对于有很多询问的题&#xff0c;一般都是先初始化。我们求出每个点到其他点的最短路径以及相同路径下最大的价值和即可。 代码&#xff1a; #include <bits/stdc.h> #define pb push_back #define a first #define b second using namespace std; type…