Skip to content

Commit 30d7175

Browse files
committed
Added null object pattern
1 parent 7329871 commit 30d7175

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Current Patterns:
2929
| [mediator](mediator.py) | an object that knows how to connect other objects and act as a proxy |
3030
| [memento](memento.py) | generate an opaque token that can be used to go back to a previous state |
3131
| [mvc](mvc.py) | model<->view<->controller (non-strict relationships) |
32+
| [null object](null_object.py) | Avoid null references by providing a default object |
3233
| [observer](observer.py) | provide a callback for notification of events/changes to data |
3334
| [pool](pool.py) | preinstantiate and maintain a group of instances of the same type |
3435
| [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) |

null_object.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
class Item:
5+
"""Represents an abstract item"""
6+
def __init__(self):
7+
self._value = None
8+
9+
def setValue(self, value):
10+
self._value = value
11+
12+
class RealItem(Item):
13+
"""Represent a valid real item"""
14+
def __init__(self, value):
15+
self._value = value
16+
17+
def printValue(self):
18+
print 'The value is: ' + str(self._value)
19+
20+
class NullItem(Item):
21+
"""Represents a null item. This is treated like real items except having no value"""
22+
def printValue(self):
23+
print '[Null object. No value]'
24+
25+
class ItemStore:
26+
"""Stores key/value pairs of items"""
27+
nullItem = NullItem()
28+
29+
def __init__(self):
30+
self._items = {};
31+
32+
def getItem(self, name):
33+
return self._items.setdefault(name, ItemStore.nullItem)
34+
35+
def setItem(self, name, value):
36+
item = self._items.setdefault(name, None)
37+
if item != None:
38+
item.value = value
39+
else:
40+
self._items[name] = RealItem(value)
41+
42+
itemstore = ItemStore()
43+
itemstore.setItem('item2', 'test item2')
44+
45+
itemstore.getItem('item2').printValue()
46+
itemstore.getItem('item3').printValue()
47+
48+
### OUTPUT ###
49+
# The value is: test item2
50+
# [Null object. No value]

0 commit comments

Comments
 (0)