python设计模(桥接模式)

2019-04-13 17:15发布

学习版本3.5.2

桥接模式,就是将抽象部分有实现部分分离开来,是它们都能够独立变化。 举一个例子:我有AB两类工人,他们都可以在12两个流水线上工作,可以随意分配他们去哪个流水线工作。 class Worker(object): pass class WorkerTypeA(Worker): def work(self): return "A type worker" class WorkerTypeB(Worker): def work(self): return "B type worker" class ProductionLine(object): def __init__(self, worker): self.worker = worker class ProductionLine1(ProductionLine): def work(self): print(self.worker.work()+" in ProductionLine1") class ProductionLine2(ProductionLine): def work(self): print(self.worker.work()+" in ProductionLine2") if __name__ == "__main__": ProductionLine1(WorkerTypeB()).work() ProductionLine2(WorkerTypeA()).work()
运行结果 B type worker in ProductionLine1 A type worker in ProductionLine2