Python設計模式-中介者模式

小屋子大俠發表於2017-06-26

Python設計模式-中介者模式

程式碼基於3.5.2,程式碼如下;

#coding:utf-8
#中介者模式

class colleague():
    mediator = None
    def __init__(self,mediator):
        self.mediator = mediator

class purchaseColleague(colleague):
    def buyStuff(self,num):
        print("PURCHASE:Bought {0}".format(num))
        self.mediator.execute("buy",num)
    def getNotice(self,content):
        print("PURCHASE:Get Notice -- {0}".format(content))

class warehoustColleague(colleague):
    total = 0
    threshold = 100
    def setThreshold(self,threshold):
        self.threshold = threshold
    def isEnough(self):
        if self.total < self.threshold:
            print("WARNING:Warning ... Stock is low ..")
            self.mediator.execute("warning",self.total)
            return False
        else:
            return True
    def inc(self,num):
        self.total += num
        print("WAREHOUSE:Increase {0}".format(num))
        self.mediator.execute("increase",num)
    def dec(self,num):
        if num > self.total:
            print("WAREHOUSE:Error ... Stock is not enough")
        else:
            self.total -= num
            print("WAREHOUSE:Decrease {0}".format(num))
            self.mediator.execute("decrease",num)
        self.isEnough()

class salesColleague(colleague):
    def sellStuff(self,num):
        print("SALES:Sell {0}".format(num))
        self.mediator.execute("sell",num)
    def getNotice(self,content):
        print("SALES:Get Notice -- {0}".format(content))

class abstractMediator():
    purchase = None
    sales = None
    warehouse = None
    def setPurchase(self,purchase):
        self.purchase = purchase
    def setWarehouse(self,warehouse):
        self.warehouse = warehouse
    def setSales(self,sales):
        self.sales = sales
    def execute(self,content,num):
        pass

class stockMediator(abstractMediator):
    def execute(self,content,num):
        print("MEDIATOR:Get Info -- {0}".format(content))
        if content == "buy":
            self.warehouse.inc(num)
            self.sales.getNotice("Bought {0}".format(num))
        elif content == "increase":
            self.sales.getNotice("Inc {0}".format(num))
            self.purchase.getNotice("Inc {0}".format(num))
        elif content == "decrease":
            self.sales.getNotice("Dec {0}".format(num))
            self.purchase.getNotice("Dec {0}".format(num))
        elif content == "warning":
            self.sales.getNotice("Stock is low {0} left".format(num))
            self.purchase.getNotice("Stock is low. Please Buy More {0}".format(num))
        elif content == "sell":
            self.warehouse.dec(num)
            self.purchase.getNotice("Sold {0}".format(num))
        else:
            pass

if __name__ == "__main__":
    mobile_mediator = stockMediator()
    mobile_purchase = purchaseColleague(mobile_mediator)
    moblie_warehouse = warehoustColleague(mobile_mediator)
    moblie_sales = salesColleague(mobile_mediator)
    mobile_mediator.setPurchase(mobile_purchase)
    mobile_mediator.setWarehouse(moblie_warehouse)
    mobile_mediator.setSales(moblie_sales)

    moblie_warehouse.setThreshold(200)
    mobile_purchase.buyStuff(300)
    moblie_sales.sellStuff(120)

中介者模式分析與解讀

中介者模式

中介者模式,用一箇中介物件來封裝一系列的物件互動。中介者使各物件不需要顯式地相互引用,從而使其耦合鬆散,而且可以獨立地改變它們之間的互動。

程式碼解讀

該例子基於的需求:銷售一旦達成訂單,銷售人員會通過系統的銷售子系統部分通知倉儲子系統,倉儲子系統會將可出倉手機數量減少,同時通知採購管理子系統當前銷售訂單;倉儲子系統的庫存到達閾值以下,會通知銷售子系統和採購子系統,並督促採購子系統採購;採購完成後,採購人員會把採購資訊填入採購子系統,採購子系統會通知銷售子系統採購完成,並通知倉庫子系統增加庫存。
1、定義了colleague類,子系統都是通過繼承該子類來實現,在該類初始化時,傳入mediator者;
2、分別定義了purchaseColleague、warehoustColleague和salesColleague三個類,分別表示採購子系統,倉庫子系統和銷售子系統,在purchaseColleague中的buyStuff、salesColleague的sellStuff方法,都是在接收到請求處理時呼叫了mediator的方法處理;在warehoustColleague倉儲子系統類中,每次呼叫inc,dec方法,都是先判斷儲存的total、threshold值是否在要求範圍內,當total數量小於threshold時,會通過呼叫mediator來通知採購子系統,當total數量增加時,通知銷售子系統倉儲數量增加;
3、通過定義abstractMediator來儲存三個子系統的例項,stockMediator通過繼承abstractMediator類,實現execute方法,來實現三個子系統在呼叫過程中的邏輯處理,以此來完成通訊。

程式碼執行結果如下:

PURCHASE:Bought 300
MEDIATOR:Get Info -- buy
WAREHOUSE:Increase 300
MEDIATOR:Get Info -- increase
SALES:Get Notice -- Inc 300
PURCHASE:Get Notice -- Inc 300
SALES:Get Notice -- Bought 300
SALES:Sell 120
MEDIATOR:Get Info -- sell
WAREHOUSE:Decrease 120
MEDIATOR:Get Info -- decrease
SALES:Get Notice -- Dec 120
PURCHASE:Get Notice -- Dec 120
WARNING:Warning ... Stock is low ..
MEDIATOR:Get Info -- warning
SALES:Get Notice -- Stock is low 180 left
PURCHASE:Get Notice -- Stock is low. Please Buy More 180
PURCHASE:Get Notice -- Sold 120

中介者模式應用場景:

1、設計類圖時,出現了網狀結構時,可以考慮將類圖設計成星型結構,這樣就可以實現中介模式;
2、適用於一組物件以定義良好但是複雜的方式進行通訊的場合;
3、想定製一個分佈在多個類中的行為,而又不想生成太多的子類的場合。

優缺點分析

優點

1、減少類與類的依賴,降低了類和類之間的耦合;
2、容易擴充套件規模。

缺點

1、當處理邏輯較多時,會造成中介者本身的複雜性較大。

相關文章