python 空对象模式_空对象模式

本文展示了如何使用Python的抽象基类(ABC)和工厂模式来创建一个客户管理系统。AbstractCustomer定义了两个抽象方法isNil和getName,RealCustomer和NullCustomer分别作为其实现。CustomerFactory类根据输入的名字返回RealCustomer或NullCustomer实例,实现了客户对象的动态创建。
摘要由CSDN通过智能技术生成

Python 代码:

from abc import abstractmethod, ABCMeta

# 创建一个抽象类

class AbstractCustomer(metaclass = ABCMeta):

name = ""

@abstractmethod

def isNil(self):

pass

@abstractmethod

def getName(self):

pass

# 创建扩展了AbstractCustomer的实体类

class RealCustomer(AbstractCustomer):

def __init__(self, inName):

self.name = inName

def getName(self):

return self.name

def isNil(self):

return Falseclass NullCustomer(AbstractCustomer):

def getName(self):

return "Not Available in Customer Database"

def isNil(self):

return True

# 创建CustomerFactory类

class CustomerFactory():

names = ["Rob", "Joe", "Julie"]

@staticmethod

def getCustomer(inName):

for aName in CustomerFactory.names:

if aName.upper() == inName.upper():

return RealCustomer(inName)

return NullCustomer()# 调用输出

if __name__ == '__main__':

customer1 = CustomerFactory.getCustomer("Rob")

customer2 = CustomerFactory.getCustomer("Bob")

customer3 = CustomerFactory.getCustomer("Julie")

customer4 = CustomerFactory.getCustomer("Laura")

print("Customers")

print(customer1.getName())

print(customer2.getName())

print(customer3.getName())

print(customer4.getName())

Siskin.xu

Siskin.xu

sis***@sohu.com9个月前 (03-10)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值