patternpythonMinor
proxy pattern in Python
Viewed 0 times
pythonproxypattern
Problem
This is my try at the proxy pattern.
What do you Pythoneers think of my attempt?
Output:
What do you Pythoneers think of my attempt?
class Image:
def __init__( self, filename ):
self._filename = filename
def load_image_from_disk( self ):
print("loading " + self._filename )
def display_image( self ):
print("display " + self._filename)
class Proxy:
def __init__( self, subject ):
self._subject = subject
self._proxystate = None
class ProxyImage( Proxy ):
def display_image( self ):
if self._proxystate == None:
self._subject.load_image_from_disk()
self._proxystate = 1
print("display " + self._subject._filename )
proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") )
proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") )
proxy_image1.display_image() # loading necessary
proxy_image1.display_image() # loading unnecessary
proxy_image2.display_image() # loading necessary
proxy_image2.display_image() # loading unnecessary
proxy_image1.display_image() # loading unnecessaryOutput:
loading HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
loading HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo1Solution
It seems like overkill to implement a class to represent the proxy pattern. Design patterns are patterns, not classes. What do you gain from your implementation compared to a simple approach like the one shown below?
Some other notes on your code:
-
It doesn't follow PEP8. In particular, "Avoid extraneous whitespace [...] immediately inside parentheses."
-
No docstrings.
-
It makes more sense to use
-
It's not necessary to append the class name to all the methods. In a class called
-
You should use new-style classes (inheriting from
class Image(object):
def __init__(self, filename):
self._filename = filename
self._loaded = False
def load(self):
print("loading {}".format(self._filename))
self._loaded = True
def display(self):
if not self._loaded:
self.load()
print("displaying {}".format(self._filename))Some other notes on your code:
-
It doesn't follow PEP8. In particular, "Avoid extraneous whitespace [...] immediately inside parentheses."
-
No docstrings.
-
It makes more sense to use
True and False for a binary condition than to use None and 1.-
It's not necessary to append the class name to all the methods. In a class called
Image, the methods should just be called load and display, not load_image and display_image.-
You should use new-style classes (inheriting from
object) to make your code portable between Python 2 and 3.Code Snippets
class Image(object):
def __init__(self, filename):
self._filename = filename
self._loaded = False
def load(self):
print("loading {}".format(self._filename))
self._loaded = True
def display(self):
if not self._loaded:
self.load()
print("displaying {}".format(self._filename))Context
StackExchange Code Review Q#20798, answer score: 7
Revisions (0)
No revisions yet.