二十三种设计模式:建造者模式篇(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()

发布了9 篇原创文章 · 获赞 0 · 访问量 416

猜你喜欢

转载自blog.csdn.net/weixin_41901939/article/details/92700208