Book Image

Mastering Python Design Patterns

By : Sakis Kasampalis
Book Image

Mastering Python Design Patterns

By: Sakis Kasampalis

Overview of this book

Table of Contents (23 chapters)
Mastering Python Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
The Factory Pattern
Index

Implementation


To demonstrate the Proxy pattern, we will implement a simple protection proxy to view and add users. The service provides two options:

  • Viewing the list of users: This operation does not require special privileges

  • Adding a new user: This operation requires the client to provide a special secret message

The SensitiveInfo class contains the information that we want to protect. The users variable is the list of existing users. The read() method prints the list of the users. The add() method adds a new user to the list. Let's consider the following code:

class SensitiveInfo:
    def __init__(self):
        self.users = ['nick', 'tom', 'ben', 'mike']

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

    def add(self, user):
        self.users.append(user)
        print('Added user {}'.format(user))

The Info class is a protection proxy of SensitiveInfo. The secret variable is the message required to be known/provided by the...