用空对象来取代客户端对Null对象的检查

优点:

  1. 能够实现对Null对象的自定义控制
  2. 加强系统的稳定性

Demo

  1. """
  2. 空对象模式
  3. """
  4. from abc import ABCMeta, abstractmethod
  5. class AbstractCustomer(metaclass=ABCMeta):
  6. @abstractmethod
  7. def is_nil(self):
  8. pass
  9. def get_name(self):
  10. pass
  11. class RealCustomer(AbstractCustomer):
  12. def __init__(self, name):
  13. self.name = name
  14. def is_nil(self):
  15. return False
  16. def get_name(self):
  17. return self.name
  18. class NullCustomer(AbstractCustomer):
  19. def is_nil(self):
  20. return True
  21. def get_name(self):
  22. return 'Not Available in Customer Database'
  23. class CustomerFactory:
  24. names = {"Rob", "Joe", "Julie"}
  25. @classmethod
  26. def get_customer(cls, name):
  27. for value in cls.names:
  28. if str.upper(value) == str.upper(name):
  29. return RealCustomer(name)
  30. return NullCustomer()
  31. if __name__ == '__main__':
  32. c_1 = CustomerFactory.get_customer('rob')
  33. c_2 = CustomerFactory.get_customer('ccc')
  34. print(c_1.get_name())
  35. print(c_2.get_name())