描述:有两个类,学生类和导师类,学生的导师类可能不存在,因此在获取学生导师名字等信息时都要先判断导师名字是否为空。重构后通过一个空导师类来处理导师为空的相应逻辑。
Before
# introduce null object class Master:
def __init__(self):
pass def setValue(self, name, major, age):
self.name = name
self.major = major
self.age = age def getName(self):
return self.name def getMajor(self):
return self.major def getAge(self):
return str(self.age) class Student:
def __init__(self, name):
self.master = None def setMaster(self, masterName):
self.master = masterName def getMaster(self):
return self.master def getMasterNameByStudent(student):
master = student.getMaster()
if master is not None:
print master.getName()
else:
print "Not exist" def getMasterMajorByStudent(student):
master = student.getMaster()
if master is not None:
print master.getMajor()
else:
print "Not exist" def getMasterAgeByStudent(student):
master = student.getMaster()
if master is not None:
print master.getAge()
else:
print "Not exist"
After
# introduce null object class Master:
def __init__(self):
pass def setValue(self, name, major, age):
self.name = name
self.major = major
self.age = age def isNull(self):
return False def getName(self):
return self.name def getMajor(self):
return self.major def getAge(self):
return str(self.age) class NoneMaster(Master):
def isNull(self):
return True def getName(self):
return "Not exist" def getMajor(self):
return "Not exist" def getAge(self):
return "Not exist" class Student:
def __init__(self, name):
self.master = None def setMaster(self, master):
self.master = master def getMaster(self):
if self.master is None:
return NoneMaster()
else:
return self.master def getMasterNameByStudent(student):
master = student.getMaster()
print master.getName() def getMasterMajorByStudent(student):
master = student.getMaster()
print master.getMajor() def getMasterAgeByStudent(student):
master = student.getMaster()
print master.getAge()
测试:
master_1 = Master()
master_1.setValue("zhang liang", "computer", 40) foo_1 = Student("wang gang")
foo_1.setMaster(master_1) foo_2 = Student("li ming") getMasterNameByStudent(foo_1)
getMasterNameByStudent(foo_2)
print getMasterMajorByStudent(foo_1)
getMasterMajorByStudent(foo_2)
print getMasterAgeByStudent(foo_1)
getMasterAgeByStudent(foo_2)
参考:重构 Martin Fowler 人民邮电出版社