python设计模式(中介者模式)

来源:互联网 发布:网络大电影制作流程 编辑:程序博客网 时间:2024/06/10 06:47

学习版本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:  1000Landlord :no, I can accept price:  1200Renter :How about  1100Landlord :no, I can accept price:  1200Landlord :How about  1100Renter :ok, I will rent. Price: 1100


原创粉丝点击