代理模式

不羁的心 提交于 2019-12-06 04:53:50

什么是代理模式?

由于某些原因,一个对象(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()

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!