Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

22 October 2010

Python singleton design pattern

How to define a class with a singleton instance? From http://python.org/dev/peps/pep-0318/, here is how:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...


However, you can also achieve singleton without such clumsy code - use python module. See here:

http://tinyurl.com/yeotybq.

A module with functions and module scope variables is handy for such purpose! So no OOP is needed?! However, be cautious with singleton design pattern. Watch this blog post from google testing blog.

16 August 2010

05 August 2010

Python bound and unbound method

The key difference between unbound and bound methods is that an unbound method is not associated with a particular instance while a bound method is. AND, delegating to a superclass implementation is the MOST FREQUENT use of unbound methods!

One common use of delegation occurs with special method __init__ in python.

27 July 2010

Delegation Pattern

A nice explanation here: http://en.wikipedia.org/wiki/Delegation_pattern

The python code example on that web page even elaborates this design pattern in more details.