首页 > 编程语言 >Python: Proxy Pattern

Python: Proxy Pattern

时间:2022-10-22 23:22:39浏览次数:47  
标签:__ enormous Python Pattern self Proxy print data class

 

DuProxy.py

# 代理模式 Proxy Pattern
from abc import ABCMeta, abstractmethod
import abc
import random


class ISubject(metaclass=ABCMeta):
    "An interface implemented by both the Proxy and Real Subject"
    @staticmethod
    @abstractmethod
    def request():
        "A method to implement"

class RealSubject(ISubject):
    "The actual real object that the proxy is representing"

    def __init__(self):
        # hypothetically enormous amounts of data
        self.enormous_data = [1, 2, 3,'geovindu','Geovin Du','涂聚文']

    def request(self):
        return self.enormous_data

class Proxy(ISubject):
    """
    The proxy. In this case the proxy will act as a cache for
    `enormous_data` and only populate the enormous_data when it
    is actually necessary
    """

    def __init__(self):
        self.enormous_data = []
        self.real_subject = RealSubject()

    def request(self):
        """
        Using the proxy as a cache, and loading data into it only if
        it is needed
        """
        if self.enormous_data == []:
            print("从真实主体提取数据")
            self.enormous_data = self.real_subject.request()
            return self.enormous_data
        print("从代理缓存中提取数据")
        return self.enormous_data


class AbstractClass(metaclass=abc.ABCMeta):
    """ interface for real and proxy object """

    @abc.abstractmethod
    def sort_digits(self, reverse=False):
        pass


class RealClass(AbstractClass):
    """ RealClass that holds a larger object """

    def __init__(self):
        self.digits = []

        for i in range(1000000):
            self.digits.append(random.random())

    def sort_digits(self, reverse=False):
        self.digits.sort()

        if reverse:
            self.digits.reverse()


class ProxyClass(AbstractClass):
    """ A proxy class that has the same interface as RealClass. """

    ref_count = 0

    def __init__(self):
        """ Creates an object if it doesn't exist and caches it otherwise """

        if not getattr(self.__class__, '缓存对象', None):
            self.__class__.cached_object = RealClass()
            print('生成新对象')
        else:
            print('使用缓存的对象')

        self.__class__.ref_count += 1
        print('引用计数:', self.__class__.ref_count)

    def sort_digits(self, reverse=False):
        print('排序方法')
        print(locals().items())

        # invokes the sort_digits method of real class
        self.__class__.cached_object.sort_digits(reverse=reverse)

    def __del__(self):
        """ Delete the object when the number of reference is 0 """
        self.__class__.ref_count -= 1

        if self.__class__.ref_count == 0:
            print('删除缓存对象')
            del self.__class__.cached_object

        print('引用计数:', self.__class__.ref_count)

  

main.py 调用

# 代理模式 Proxy Pattern
duSubject = DuProxy.Proxy()
# use SUBJECT
print(id(duSubject))
# load the enormous amounts of data because now we want to show it.
print(duSubject.request())
# show the data again, but this time it retrieves it from the local cache
print(duSubject.request())
print("\n")
proxA = DuProxy.ProxyClass()
print()

proxB = DuProxy.ProxyClass()
print()

proxC = DuProxy.ProxyClass()
print()

proxA.sort_digits(reverse=True)
print()

print('删除对象 proxA')
del proxA

print('删除对象 proxB')
del proxB

print('删除对象 proxC')
del proxC

  

输出:

1830765068000
从真实主体提取数据
[1, 2, 3, 'geovindu', 'Geovin Du', '涂聚文']
从代理缓存中提取数据
[1, 2, 3, 'geovindu', 'Geovin Du', '涂聚文']


生成新对象
引用计数: 1

生成新对象
引用计数: 2

生成新对象
引用计数: 3

排序方法
dict_items([('self', <DuProxy.ProxyClass object at 0x000001AA4219FFA0>), ('reverse', True)])

删除对象 proxA
引用计数: 2
删除对象 proxB
引用计数: 1
删除对象 proxC
删除缓存对象
引用计数: 0

  

 

 

 

 

 

标签:__,enormous,Python,Pattern,self,Proxy,print,data,class
From: https://www.cnblogs.com/geovindu/p/16817584.html

相关文章

  • GPU编程实战:基于Python和CUDA 电子书 pdf
    作者:布莱恩·图奥迈宁(BrianTuomanen)出版社:人民邮电出版社原作名:Hands-OnGPUProgrammingwithPythonandCUDA 链接:GPU编程实战:基于Python和CUDA  本书......
  • 30 个 Python 技巧,加速你的数据分析处理速度
    pandas的下载 使用命令下载:pipinstallpandas  或者自行下载whl文件安装https://www.lfd.uci.edu/~gohlke/pythonlibs/  创建DataFrame数据pd_da......
  • python 调用Adobe Acrobat 将pdf 转 excel
    最近需要批量转换一些pdf扫描件,就开始找相关的python包花了不少时间试了下pdfplumber,pypdf2,camelot这几个包发现都不能成功的转化,原因就在于手上的pdf是扫描件,......
  • python的字符串截取
    截取规则:实际Python字符串截取的规则为“前闭后开”简单规律总结:字符串截取一般有两种形式[:]这种形式就是从哪截取到哪里如果是负数就从后往前找[::]这种......
  • 【Web开发】Python实现Web服务器(Flask测试统计图表)
    1、前言提示:Flask是一个用python语言基于Werkzeug工具箱编写的轻量级web开发框架,它主要面向需求简单,项目周期短的小应用。Flask是一个使用Python编写的轻量级Web应用......
  • 【Web开发】Python实现Web服务器(Flask测试后台框架模板)
    1、前言提示:Flask是一个用python语言基于Werkzeug工具箱编写的轻量级web开发框架,它主要面向需求简单,项目周期短的小应用。Flask是一个轻量级的可定制框架,使用Python语言......
  • python内置方法__getitem__,__delitem__,__setitem__
    classFoo:def__init__(self,name):self.name=namedef__getitem__(self,item):print('getitem')print(item)returns......
  • Python列表操作
    目录导航:1.for循环遍历列表2.range()函数3.对数字列表的统计操作4.列表切片5.复制列表6.元组的定义7.修改元组  1.for循环遍历......
  • Python第七章实验报告
    一.实验名称:《零基础学Python》第7章面向对象程序设计二.实验环境:IDLEShell3.9.7三.实验内容:5道实例、4道实战四.实验过程:实例01创建大雁类并定义飞行方法点......
  • (数据科学学习手札145)在Python中利用yarl轻松操作url
    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes1简介大家好我是费老师,在诸如网络爬虫、web应用开发等场景中,我们需要利......