保护代理模式

import abc

# 客户端直接实例化SensitiveInfo类可以使用全部方法,为增加安全,将SensitiveInfo定义为抽象基类,不能直接实例化
class SensitiveInfo(metaclass=abc.ABCMeta):
    def __init__(self):
        self.users = ['nick', 'tom', 'ben', 'mike']

    def read(self):
        print('There are {} users: {}'.format(len(self.users), self.users))

    @abc.abstractmethod
    def add(self, user):
        self.users.append(user)
        print('Add user {}'.format(user))


class Info(SensitiveInfo):
    def __init__(self):
        super(Info, self).__init__()
        self.secret = '31415926'  # 将密码放置到文件或数据库中

    def add(self, user):
        passwd = input('请输入密钥')
        super().add(user) if passwd == self.secret else print('passwd is wrong')


if __name__ == '__main__':
    info = Info()
    info.read()
    info.add('jay')
    info.read()

输出结果

There are 4 users: ['nick', 'tom', 'ben', 'mike']
请输入密钥31415926
Add user jay
There are 5 users: ['nick', 'tom', 'ben', 'mike', 'jay']

你可能感兴趣的:(保护代理模式)