首頁 » 設計模式 » 中介者(Mediator)

中介者(Mediator)

作者:

分類:

中介者(Mediator)

概念

中介者模式(又稱協調者模式)是一種行為型模式,顧名思義此模式會由一個第三方的類別來協調類別之間的訊息傳遞,藉此保持原有類別的獨立性及類別間的低耦合,中介者類別會負責定義類別之間的互動。

範例

//**************
//* author: cian
//* 20231107
//**************

enum UserType
{
    Operator,
    Admin
}

interface IMediator {
    void Add(Control control, UserType type);
    void Login(UserType type);
}

class UIMediator : IMediator
{
    private readonly Dictionary<UserType, Colleague> colleagueDict = new List<UserType, Colleague>();
    
    public void Add(UserType type, Colleague colleague)
    {   
        if(!colleagueDict.ContainsKey(type))
        {
            colleagueDict.Add(type, colleague);
        }
    }
    
    public void Login(UserType type)
    {
        //check key contains too...
        //here is the UI enable logic.
        switch(type)
        {
            case UserType.Operator:
                colleagueDict[UserType.Operator].SetUInable(true);
                colleagueDict[UserType.Admin].SetUInable(false);
                break;
            case UserType.Admin:
                colleagueDict[UserType.Operator].SetUInable(true);
                colleagueDict[UserType.Admin].SetUInable(true);
                break;
        }
    }
    
    public void Logout() //back to Operator Mode...
    {
         colleagueDict[UserType.Operator].SetUInable(true);
         colleagueDict[UserType.Admin].SetUInable(false);
    }
}

class Colleague 
{
    private readonly List<Control> controls = new List<Control>();
    
    public void AddControl(Control control)
    {
        controls.Add(control);
    }
    
    public void SetUInable(bool enable)
    {
        foreach(var item in controls)
        {
            item.Enable = enable;
        }
    }
}

class MainApp
{
    static void Main(string[] args)
    {
        Colleague operatorUI = new Colleague();
        Colleague adminUI = new Colleague();
        //Add control to each colleague base on UserType..
        
        UIMediator mediator = UIMediator();
        mediator.Add(operatorUI);
        mediator.Add(adminUI);
        
        mediator.Login(UserType.Admin);
        mediator.Logout();
    }
}

結語

以介面權限管理作為範例沒能完全展現Mediator的樣貌,Colleague類別難做更多的延伸,也因為此模式沒有明確定義Mediator內運作的關係,所以就用自己的想法來套用。

原本權限管理是打算用狀態模式實作,但想到當Control一多會變很肥就作罷。反而Mediator做為權限管理是蠻實用的,可以很容易的把Control做分級。

以上為學習過程的問題紀錄
如果文章有誤,歡迎前輩留言請不吝指教。

「cian」的個人頭像

留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *