您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 设计模式