Python 计划模式之制作者模式

[复制链接]
发表于 2026-2-12 22:24:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
制作者(builder)模式属于创建型模式,制作者模式一样寻常有两种范例的应用
制作者模式中的简单版本

徐徐复杂的标题

假设如今必要创建一个用户对象,那么你会如许实当代码
  1. class User:
  2.     def __init__(self, name):
  3.         self.name = name
  4. user = User("jack")
复制代码
厥后你必要为这个用户对象引入其他的属性:生日、住址、身高、体重、爱好,差别的用户在创建时不乐意提供此中一些信息,于是你实现了下面的版本:
  1. class User:
  2.     def __init__(self, name, age=None,birth_date=None,address=None,heigh=None,weight=None,hobby=None):
  3.         self.name = name
  4.         self.age = age
  5.         self.birth_date = birth_date
  6.         self.address = address
  7.         self.heigh = heigh
  8.         self.weight = weight
  9.         self.hobby = hobby
  10. user = User("John", heigh=165,weight=58,hobby="reading")
复制代码
可以看到随着对象的属性越来越多,我们的构造函数的参数列表越来越长。这里由于使用了关键字参数的关系,以是标题并不显着,如果使用位置参数,那么使用者在使用时就必须记着参数的位置,乃至对于没有的属性必要放置None值:
  1. def __init__(self, name, age,birthday,address,heigh,weight,hobby):
  2.     ...
  3. User("Lucy",17,None,None,68,None,None)
复制代码
固然这个标题也不是不能担当,让我们继续增长标题标复杂度,如果如今我们还必要对一些属性举行校验大概转化处置惩罚,那么你大概会这么修改代码:
  1. class User:
  2.     def __init__(self, name, age=None,birth_date=None,address=None,heigh=None,weight=None,hobby=None):
  3.         self.name = name
  4.         self.age = age if isinstance(age,int) and age > 0 else None
  5.         self.birth_date = birth_date
  6.         self.address = address
  7.         self.heigh = heigh if isinstance(heigh, int) else None
  8.         self.weight = weight if isinstance(weight, int) else None
  9.         self.hobby = self.set_hobby(hobby)
  10.     def set_hobby(self, hobby):
  11.         if isinstance(hobby, list):
  12.             hobby = ",".join(hobby)
  13.         return hobby
  14. user = User("John", heigh=165,weight=58,hobby=["reading","running"])
复制代码
在这个版本中,构造参数依然很多,但set_hobby的出现,让我们开始思索属性的添加为什么不接纳调用实例函数的方式设置?于是我们修改了整个 User 的实现
  1. class User:
  2.     def __init__(self, name):
  3.         self.name = name
  4.         self.label = None
  5.    
  6.     def get_user_info(self):
  7.         return self.__dict__
  8.     def add_age(self,age:int):
  9.         if age < 0:
  10.             raise ValueError("Age should be > 0!!!")
  11.         self.age = age
  12.     def add_birthday(self,birthday):
  13.         self.birthday = birthday
  14.     def add_address(self,address:str):
  15.         self.address = address
  16.     def add_height(self,height:int):
  17.         self.height = height
  18.     def add_weight(self,weight:int):
  19.         self.weight = weight
  20.     def add_hobby(self, hobby):
  21.         if isinstance(hobby, list):
  22.             hobby = ",".join(hobby)
  23.         self.hobby = hobby
  24. def main():
  25.     user = User("John")
  26.     user.add_height(
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表