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

本文介绍了一种设计模式——中介者模式,并通过一个租房场景的例子来展示如何使用该模式。通过中介者来协调租客和房东之间的价格协商过程,使得双方不需要直接相互作用,从而降低了系统的耦合度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习版本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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值