二十三种设计模式:建造者模式篇(Python)

二十三种设计模式:建造者模式篇Python


(1)介绍
建造者模式(Builder Pattern),一种常用设计模式,属于创建型模式。
使用多个简单对象构建复杂对象。
(2)解决问题
由于需求变化,复杂对象经常面临剧烈变化。
(3)使用场景
零件不变,但组合多变。
(4)核心
组装顺序很重要
原料:石头,木材,茅草
石头+石头=地基
石头+木材=墙壁
木材+茅草=屋顶
地基+墙壁+屋顶=房子

(5)代码
(个人练习)

class Rock():
    '''石头类'''
    pass
class floorRock(Rock):
    '''作为地基的石头'''
    pass
class wallRock(Rock):
    '''作为墙壁的石头'''
    pass

class Wood():
    '''木材类'''
    pass
class wallWood(Wood):
    '''作为墙壁的木材'''
    pass
class roofWood(Wood):
    '''作为屋顶的木材'''
    pass

class Thatch():
    '''茅草类'''
    pass
class roofThatch(Thatch):
    '''作为屋顶的茅草'''
    pass

class order():
    '''命令规则'''
    rock = ''
    wood = ''
    thatch = ''
    def __init__(self,orderBuilder):
        self.rock = orderBuilder.bRock
        self.wood = orderBuilder.bWood
        self.thatch = orderBuilder.bThatch

    def show(self):
        if self.rock and self.wood and not self.thatch:
            print('墙壁铸造成功!')
        elif self.wood and self.thatch and not self.rock:
            print('屋顶铸造成功!')
        elif self.rock and not (self.thatch and self.wood):
            print('地基铸造成功!')


class orderBuilder():
    '''执行命令'''
    bRock = None
    bWood = None
    bThatch = None
    def add(self,xRock=bRock,xWood=bWood,xThatch=bThatch):
        '''添加方法'''
        self.bRock = xRock
        self.bWood = xWood
        self.bThatch = xThatch
    def build(self):
        '''建造方法'''
        return order(self)


def main():
    order_builder = orderBuilder()
    order_builder.add(xRock=floorRock(),xWood=Wood())
    order_builder.build().show()


if __name__ == '__main__':
    main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值