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

    设计模式之代理模式

    from abc import ABCMeta,abstractmethod
    
    
    # -------------------------接口,用于约束
    class Theme(metaclass=ABCMeta):
        @abstractmethod
        def get_content(self):
            pass
    
    class RealTheme(Theme):
        def __init__(self,filepath):
            self.filepath = filepath
            print('获取文件%s详情'%self.filepath)
            f = open(filepath)
            self.content = f.read()
            f.close()
        def get_content(self):
            return self.content
        def set_content(self,content):
            #
            f = open(self.filepath,'w')
            f.write(content)
            f.close()
    
    
    class ProxyA(Theme):
        def __init__(self,filepath):
            self.theme = RealTheme(filepath)
        def get_content(self):
            return self.theme.get_content()
    
    
    
    class ProxyB(Theme):
        # 虚代理
        def __init__(self,filepath):
            self.filepath = filepath
            self.theme = None
        def get_content(self):
            # 按需分配,根据需要去创建对象,减少资源的浪费
            if not self.theme:
                self.theme = RealTheme(self.filepath)
            return self.theme.get_content()
    
    
    
    class ProxyC(Theme):
        # 保护代理
        def __init__(self,filepath):
            self.theme = RealTheme(filepath)
        def get_content(self):
            return self.theme.get_content()
        def set_content(self):
            # 进行权限配置,根据不同身份来配置权限控制用户的写操作
            raise PermissionError
    
    
        
    # b = ProxyB('abc.txt')
    # print(b.get_content())
    
    c = ProxyC('abc.txt')
    print(c.get_content())
  • 相关阅读:
    字符串删减
    iOS-AFNetworking与ASIHTTPRequest的区别
    iOS-清理缓存
    iOS-addSubView时给UIView添加效果
    iOS-明杰解决字段冲突,及数组映射
    iOS-开发将文本复制到剪切板
    iOS-加载html字符串
    iOS-UILabel加线
    iOS-获取webView的高度
    iOS-plist文件的写读
  • 原文地址:https://www.cnblogs.com/aadmina/p/8977681.html
Copyright © 2011-2022 走看看