diff --git a/README.md b/README.md index 1fdee48a..2938181f 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ Current Patterns: | [mediator](mediator.py) | an object that knows how to connect other objects and act as a proxy | | [memento](memento.py) | generate an opaque token that can be used to go back to a previous state | | [mvc](mvc.py) | model<->view<->controller (non-strict relationships) | +| [null object](null_object.py) | Avoid null references by providing a default object | | [observer](observer.py) | provide a callback for notification of events/changes to data | | [pool](pool.py) | preinstantiate and maintain a group of instances of the same type | | [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) | diff --git a/null_object.py b/null_object.py new file mode 100644 index 00000000..fae52a3e --- /dev/null +++ b/null_object.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +Author: https://github.com/fousteris-dim +Reference: http://en.wikipedia.org/wiki/Null_Object_pattern +""" + +class Item: + """Represents an abstract item""" + def __init__(self): + self._value = None + + def setValue(self, value): + self._value = value + +class RealItem(Item): + """Represent a valid real item""" + def __init__(self, value): + self._value = value + + def printValue(self): + print 'The value is: ' + str(self._value) + +class NullItem(Item): + """Represents a null item. This is treated like real items except having no value""" + def printValue(self): + print '[Null object. No value]' + +class ItemStore: + """Stores key/value pairs of items""" + nullItem = NullItem() + + def __init__(self): + self._items = {}; + + def getItem(self, name): + return self._items.setdefault(name, ItemStore.nullItem) + + def setItem(self, name, value): + item = self._items.setdefault(name, None) + if item != None: + item.setValue(value) + else: + self._items[name] = RealItem(value) + +itemstore = ItemStore() +itemstore.setItem('item2', 'test item2') + +itemstore.getItem('item2').printValue() +itemstore.getItem('item3').printValue() + +### OUTPUT ### +# The value is: test item2 +# [Null object. No value] \ No newline at end of file