python设计模式(中介者模式)
2017-11-07 15:27
411 查看
学习版本3.5.2
#学习版本3.5.2#中介者模式定义:用一个中介者对象封装一些列的对象交互,中介者使各对象不需要显
#式地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互
#举例子:通过房产中介租房子
class Person(object):
def __init__(self, price):
self.price = price
def getPrice(self):
return self.price
#租客
class Renter(Person):
#对中介转达的价格给予反应
def getRentPrice(self, price):
print(self.__class__.__name__,":")
if price <= self.price:
print("ok, I will rent. Price:", self.price)
else:
print("no, I can accept price: ", self.price)
#告诉中介自己能接受的价格
def showPriceICanRent(self, price, mediator):
self.price = price
print(self.__class__.__name__,":")
print("How about ",self.price)
mediator.showPriceICanRent()
class Landlord(Person):
#对中介转达的价格给予反应
def getRentPrice(self, price):
print(self.__class__.__name__,":")
if price >= self.price:
print("ok, I will rent to him. Price:", self.price)
else:
print("no, I can accept price: ", self.price)
#告诉中介自己能接受的价格
def showRentPrice(self, price, mediator):
self.price = price
print(self.__class__.__name__,":")
print("How about ",self.price)
mediator.showRentPrice()
class Mediator(object):
def __init__(self, landlord, renter):
self.landlord = landlord
self.renter = renter
#告诉租客房东事先定的价格
def showRentPrice(self):
self.renter.getRentPrice(self.landlord.getPrice())
#告诉房东租客的心里价位
def showPriceICanRent(self):
self.landlord.getRentPrice(self.renter.getPrice())
if __name__ == "__main__":
renter = Renter(1000)#心里价位为1000的租客
landlord = Landlord(1200)#心里价位为1200的房东
mediator = Mediator(landlord, renter)#中介
mediator.showRentPrice()#告诉租客房东事先定的价格
mediator.showPriceICanRent()#告诉房东租客的心里价位
renter.showPriceICanRent(1100, mediator)#租客调整了自己的心里价位并让中介转告
landlord.showRentPrice(1100, mediator)#房东调整了自己的心里价位并让中介转告
运行结果
Renter :
no, I can accept price: 1000
Landlord :
no, I can accept price: 1200
Renter :
How about 1100
Landlord :
no, I can accept price: 1200
Landlord :
How about 1100
Renter :
ok, I will rent. Price: 1100
相关文章推荐
- 23种设计模式之python实现--中介者模式
- [Python设计模式] 第25章 联合国维护世界和平——中介者模式
- 设计模式十九(中介者模式,python语言实现)
- 设计模式-行为型模式,python 中介者模式
- 设计模式-中介者模式-mediator-python
- Python设计模式-中介者模式
- 设计模式 行为模式 中介者模式 c语言 版本实现
- 设计模式之python版(六)--原型模式
- Java 设计模式之中介者模式
- Python设计模式系列之三: 创建型Factory Method模式
- Python设计模式之观察者模式简单示例
- 23种设计模式4--行为型模式(策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式)
- [Python设计模式] 第18章 游戏角色备份——备忘录模式
- 设计模式之中介者模式
- 23种设计模式(7):中介者模式
- 设计模式之--中介者模式
- Python设计模式--适配器模式
- 设计模式:中介者模式
- 设计模式之中介者模式
- 设计技巧22:Mediator 中介者模式 顾问,沟通所有复杂组件之间的关系