zoukankan      html  css  js  c++  java
  • Python中单例模式的装饰器实现详解

    Python中单例模式的实现方法有多种,但在这些方法中属装饰器版本用的广,因为装饰器是基于面向切面编程思想来实现的,具有很高的解耦性和灵活性。

    单例模式定义:具有该模式的类只能生成一个实例对象。

    先将代码写上

      #创建实现单例模式的装饰器

    1  def singleton (cls, *args, **kwargs):

    2    instances = {}

    3    def get_instance (*args, **kwargs):

    4      if cls not in instances:

    5        instances[cls] = cls(*args, **kwargs)

    6      return instances[cls]

    7    return get_instance

    代码分析:第1行,创建外层函数singleton,可以传入类

         第2行,创建一个instances字典用来保存单例

           第3行,创建一个内层函数来获得单例

           第4,5,6行, 判断instances字典中是否含有单例,如果没有就创建单例并保存到instances字典中,然后返回该单例

           第7行, 返回内层函数get_instance

      #创建一个带有装饰器的类

      @singleton

      class Student:

        def __init__(self, name, age):

          self.name = name

          self.age = age

    在Python中认为“一切皆对象”,类(元类除外)、函数都可以看作是对象,既然是对象就可以作为参数在函数中传递,我们现在来调用Student类来创建实例,看看实现过程。

    #创建student实例

    student = Student(jiang, 25)

    @singleton相当于Student = singleton(Student),在创建实例对象时会先将 Student 作为参数传入到 singleton 函数中,函数在执行过程中不会执行 get_instance 函数(函数只有调用才会执行),直接返回get_instance函数名。

    此时可以看作Student = get_instance,创建实例时相当于student = get_instance(jiang, 25),调用get_instance 函数,先判断实例是否在字典中,如果在直接从字典中获取并返回,如果不在执行 instances [cls] = Student(jiang, 25),然后返回该实例对象并赋值非student变量,即student = instances[cls]。

  • 相关阅读:
    软件杯-题目和插件
    基于《河北省重大技术需求征集系统》的可用性和可修改性战术分析
    基于淘宝网的系统质量属性六大场景
    架构漫谈读后感
    06掌握需求过程阅读笔记之一
    大道至简读后感以及JAVA伪代码
    K8S学习笔记
    事务的七种传播类型、及案例
    香港身份证规则
    oracle函数
  • 原文地址:https://www.cnblogs.com/captainwade/p/10873074.html
Copyright © 2011-2022 走看看