Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
55 changes: 55 additions & 0 deletions null_object.py
Original file line number Diff line number Diff line change
@@ -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]