python设计模式第七天建造者模式
Posted liuzhiqaingxyz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python设计模式第七天建造者模式相关的知识,希望对你有一定的参考价值。
1. 建造者模式UML图
2.应用场景
(1)专门创建具有符合属性的对象
3.代码实现
#!/usr/bin/env python #! _*_ coding: UTF-8 _*_ from abc import ABCMeta, abstractmethod class House(object): def __init__(self): pass def makeFloor(self, floor): self.floor = floor def makeWall(self, wall): self.wall = wall def getFloor(self): return self.floor def getWall(self): return self.wall class Builder(object): __metaclass__ = ABCMeta @abstractmethod def makeFloor(self): pass @abstractmethod def makeWall(self): pass @abstractmethod def getHouse(self): pass @abstractmethod def getHouse(self): pass class PingFangBuilder(Builder): def __init__(self): self.house = House() def makeFloor(self): self.house.makeFloor("平房地板") def makeWall(self): self.house.makeWall("平房墙") def getHouse(self): return self.house class Director(object): def __init__(self, builder): self.__builder = builder def makeHouse(self): self.__builder.makeFloor() self.__builder.makeWall() if __name__ == "__main__": ‘‘‘使用最原始的方式‘‘‘ house = House() house.makeFloor("地板") house.makeWall("墙") print house.getFloor() print house.getWall() ‘‘‘使用建造者模式‘‘‘ builder = PingFangBuilder() director = Director(builder) director.makeHouse() house = builder.getHouse() print house.getFloor() print house.getWall()
结果:
/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day7_builder/builder_test.py
地板
墙
平房地板
平房墙
Process finished with exit code 0
以上是关于python设计模式第七天建造者模式的主要内容,如果未能解决你的问题,请参考以下文章