zoukankan      html  css  js  c++  java
  • 代理模式

    什么是代理模式?

    由于某些原因,一个对象(A)无法直接访问目标对象(B),而代理对象(P)可以直接访问目标对象(B),这时对象(A)可以和代理对象(P)建立关联, 通过代理对象(P)去访问目标对象(B)

    UML类图

    静态代理

    import abc
    '''
    有个二B 害羞 不敢去吃东西,叫别人去帮他拿个来吃。
    '''
    
    
    class ITest(abc.ABC):
        def test(self): ...
    
    
    class OErb(ITest):
    
        def test(self):
            print("~~~吃吃吃吃吃吃吃吃吃~~~")
    
    
    class OErbProxy(ITest):
    
        def __init__(self, o: ITest):
            self.o = o
    
        def test(self):
            print("路费5元,你快吃吧 二B")
            self.o.test()
    
    
    xm = OErb()
    
    erproxy = OErbProxy(xm)
    
    erproxy.test()

    动态代理

    不知道是对是错,随便看看得了

    import abc
    '''
    动态代理
    '''
    
    class AbsTest:
        @abc.abstractmethod
        def test(self): ...
    
    
    class OTest(AbsTest):
        def test(self):
            print("dasd")
    
        def bbb(self):
            print("bbb")
    
    
    class ProxyFactory:
        def __init__(self, o: AbsTest):
            self.o = o
    
        # 拦截器
        def __getattribute__(self, item):
            o = object.__getattribute__(self, 'o')
            attr = object.__getattribute__(o, item)
    
            def func(*args, **kw):
                print("额外操作")
                return attr(*args, **kw)
            return func
    
    
    o = OTest()
    proxy = ProxyFactory(o)
    
    proxy.test()
  • 相关阅读:
    08day 操作命令以及目录结构
    换工作
    json转为字典
    快速排序
    冒泡排序
    python函数-生成器
    关键字global
    函数的定义和参数调用
    count()函数与center()函数
    python字符串常用函数:strip()
  • 原文地址:https://www.cnblogs.com/whnba/p/11962805.html
Copyright © 2011-2022 走看看