設(shè)計模式2-中介者模式

問題:

在軟件的開發(fā)過程中怜跑,勢必會碰到這樣一種情況样勃,多個類或多個子系統(tǒng)相互交互吠勘,而且交互很繁瑣,導致每個類都必須知道他需要交互的類峡眶,這樣它們的耦合會顯得異常厲害剧防。牽一發(fā)而動全身,
好了辫樱,既然問題提出來了峭拘,那有請我們這期的主角——中介者模式出場吧!

中介者模式

用一個中介者對象來封裝一系列的對象交互狮暑。中介者使得各對象不需要顯式地相互引用鸡挠,從而使其松散耦合,而且可以獨立地改變它們之間的交互搬男。

中介者模式結(jié)構(gòu)圖

例子(oc版):

#import <UIKit/UIKit.h>

@interface DPMredViewController : UIViewController

@end
#import "DPMredViewController.h"
#import "DPMediator.h"

@interface DPMredViewController ()

@end

@implementation DPMredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"我是紅色控制器";
    
    [self setupUI];
}

- (void)setupUI{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor blackColor];
    button.frame = CGRectMake(self.view.bounds.size.width/2-30, self.view.bounds.size.height/2-30, 60, 60);
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 30;
    button.layer.masksToBounds = YES;
    [button setTitle:@"下一個" forState:UIControlStateNormal];
    [self.view addSubview:button];
}

- (void)clickButton:(UIButton *)sender{
    
    [[DPMediator shareInstance] requestNextViewControllerWithType:greenVCType];
}


@end


#import <UIKit/UIKit.h>

@interface DPMgreenViewController : UIViewController

@end
#import "DPMgreenViewController.h"
#import "DPMediator.h"

@interface DPMgreenViewController ()

@end

@implementation DPMgreenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    self.title = @"我是綠色控制器";

    [self setupUI];
}

- (void)setupUI{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor blackColor];
    button.frame = CGRectMake(self.view.bounds.size.width/2-30, self.view.bounds.size.height/2-30, 60, 60);
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 30;
    button.layer.masksToBounds = YES;
    [button setTitle:@"下一個" forState:UIControlStateNormal];
    [self.view addSubview:button];
}

- (void)clickButton:(UIButton *)sender{
    
    [[DPMediator shareInstance] requestNextViewControllerWithType:blueVCType];
}


@end

#import <UIKit/UIKit.h>

@interface DPMblueViewController : UIViewController

@end
#import "DPMblueViewController.h"
#import "DPMediator.h"

@interface DPMblueViewController ()

@end

@implementation DPMblueViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blueColor];
    self.title = @"我是藍色控制器";
    
    [self setupUI];
}

- (void)setupUI{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor blackColor];
    button.frame = CGRectMake(self.view.bounds.size.width/2-30, self.view.bounds.size.height/2-30, 60, 60);
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 30;
    button.layer.masksToBounds = YES;
    [button setTitle:@"下一個" forState:UIControlStateNormal];
    [self.view addSubview:button];
}

- (void)clickButton:(UIButton *)sender{

    [[DPMediator shareInstance] requestNextViewControllerWithType:defaultVCType];
}

@end


#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, VCType) {
    
    defaultVCType,
    redVCType,
    greenVCType,
    blueVCType
};

@interface DPMediator : NSObject

+ (DPMediator *)shareInstance;

- (void)requestNextViewControllerWithType:(VCType) vctype;

@end
#import "DPMediator.h"
#import "AppDelegate.h"
#import "DPMredViewController.h"
#import "DPMgreenViewController.h"
#import "DPMblueViewController.h"

@interface DPMediator()


@end

@implementation DPMediator

+ (DPMediator *)shareInstance{
    static DPMediator * instance = nil;
    static dispatch_once_t tokeOnce;
    dispatch_once(&tokeOnce, ^{
        instance = [[DPMediator alloc] init];
    });
    
    return instance;
}

- (void)requestNextViewControllerWithType:(VCType) vctype{

    UIViewController * viewController =   [UIApplication sharedApplication].keyWindow.rootViewController.childViewControllers.lastObject;
    
    switch (vctype) {
        case redVCType:
        {
            DPMredViewController * vc = [[DPMredViewController alloc] init];
            [viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
        case greenVCType:
        {
            DPMgreenViewController * vc = [[DPMgreenViewController alloc] init];
            [viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
        case blueVCType:
        {
            DPMblueViewController * vc = [[DPMblueViewController alloc] init];
            [viewController.navigationController pushViewController:vc animated:YES];

        }
            break;
        case defaultVCType:
        {
            [viewController.navigationController popToRootViewControllerAnimated:YES];
        }
            break;
        default:
            break;
    }
}


@end

//開始使用
#import "DPMmainViewController.h"
#import "DPMediator.h"
#import "DPMediatorWithC++Show.h"

@interface DPMmainViewController ()

@end

@implementation DPMmainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    self.title = @"中介者模式";
    
    [self setupUI];
}


- (void)setupUI{
    
    UIButton * button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 setTitle:@"oc版" forState:UIControlStateNormal];
    button1.frame = CGRectMake(30, 200, 60, 60);
    button1.backgroundColor = [UIColor redColor];
    button1.layer.cornerRadius = 30;
    button1.layer.masksToBounds = YES;
    [button1 addTarget:self action:@selector(clickOCButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
    
    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button2 setTitle:@"c++版" forState:UIControlStateNormal];
    button2.frame = CGRectMake(self.view.bounds.size.width-30-60, 200, 60, 60);
    button2.backgroundColor = [UIColor redColor];
    button2.layer.cornerRadius = 30;
    button2.layer.masksToBounds = YES;
    [button2 addTarget:self action:@selector(clickCCButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];

    
    
}


- (void)clickOCButton:(UIButton *)sender{

    [[DPMediator shareInstance] requestNextViewControllerWithType:redVCType];

}


@end

例子(C++版):

#include <iostream>
#include <vector>
#include <string>

using namespace std;

//抽象的同事類
class Colleage{
    
private:
    string name;
    string content;
public:
    
    Colleage(string n = " "):name(n){};
    
    void setName(string name){
        this->name = name;
    }
    
    string getName(){
        return this->name;
    }
    
    void setContent(string content){
        this->content = content;
    }
    
    string getContent(){
        return this->content;
    }
    
    virtual void talk() {};
};

// 具體的同事類:班長
class Monitor : public Colleage{
public:
    Monitor(string n = ""): Colleage(n){};
    
    virtual void talk(){
        cout<<"大班長說:"<<getContent()<<endl;
    }
};

//具體的同事類:團支書
class TuanZhiShu: public Colleage{

public:
    TuanZhiShu(string n = " "): Colleage(n){};
    
    virtual void talk (){
        cout<<"團支書說:"<<getContent()<<endl;
    }
};

//具體的同事類:同學A
class StudentA: public Colleage{
public:
    StudentA(string n = ""):Colleage(n){};
    
    virtual void talk(){
        cout<<"學生A說:"<<getContent()<<endl;
    }
};

//具體的同事類:同學B
class StudentB : public Colleage{
    
public:
    
    StudentB(string n = ""): Colleage(n){};
    
    virtual void talk(){
        cout << "同學B說:"<<getContent()<<endl;
    }
    
};


//抽象中介者
class Mediator{

public:
    vector<Colleage *> studentList;
    virtual void addStudent(Colleage * student){
        studentList.push_back(student);
    }
    
    virtual void notify(Colleage * student){};
    virtual void chart(Colleage * student1, Colleage * student2) {};
    
};

//具體中介者QQ通訊平臺
class QQMediator : public Mediator{

public:
    virtual void notify(Colleage * student){
        student->talk();
        for (int i =0; i<studentList.size(); i++) {
            if (student != studentList[i]) {
                studentList[i]->talk();
            }
        }
    }
    
    virtual void chart(Colleage * student1, Colleage * student2){
        student1->talk();
        student2->talk();
    }
};

//使用
- (void)clickCCButton:(UIButton *)sender{
    
    QQMediator qq;
    Monitor  studentMonitor("Vincent");
    TuanZhiShu studentTuanZhiShu("Robort");
    StudentA studentA("Sam");
    StudentB studentB("Tom");

    cout<<"下面的班長發(fā)布一個通知的場景:"<<endl;
    //將同學們加入到qq群中
    qq.addStudent(&studentMonitor);
    qq.addStudent(&studentTuanZhiShu);
    qq.addStudent(&studentA);
    qq.addStudent(&studentB);
    //設(shè)置大家的回復消息
    studentMonitor.setContent("明天下午2點開年紀會拣展,收到回復");
    studentTuanZhiShu.setContent("知道了,肯定到");
    studentA.setContent("收到了缔逛,但是可能晚點到");
    studentB.setContent("收到了备埃,但是明天考試");
    //開始發(fā)通知
    qq.notify(&studentMonitor);
    cout<<endl<<"下面是兩個同學的私下交流"<<endl;
    studentMonitor.setContent("你覺得我們的老師怎么樣");
    studentA.setContent("我覺得不好");
    qq.chart(&studentMonitor, &studentA);
}

下面的班長發(fā)布一個通知的場景:
大班長說:明天下午2點開年紀會,收到回復
團支書說:知道了褐奴,肯定到
學生A說:收到了按脚,但是可能晚點到
同學B說:收到了,但是明天考試

下面是兩個同學的私下交流
大班長說:你覺得我們的老師怎么樣
學生A說:我覺得不好

總結(jié):

中介者模式很容易在系統(tǒng)中應(yīng)用敦冬,也很容易在系統(tǒng)中誤用辅搬。當系統(tǒng)出現(xiàn)了多對多交互復雜的對象群時,不要急于使用中介者模式匪补,而要先反思你在系統(tǒng)上設(shè)計是否合理伞辛。
優(yōu)點就是集中控制,減少了對象之間的耦合度夯缺。缺點就是太過于集中蚤氏。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市踊兜,隨后出現(xiàn)的幾起案子竿滨,更是在濱河造成了極大的恐慌,老刑警劉巖捏境,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件于游,死亡現(xiàn)場離奇詭異,居然都是意外死亡垫言,警方通過查閱死者的電腦和手機贰剥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來筷频,“玉大人蚌成,你說我怎么就攤上這事前痘。” “怎么了担忧?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵芹缔,是天一觀的道長。 經(jīng)常有香客問我瓶盛,道長最欠,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任惩猫,我火速辦了婚禮芝硬,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘帆锋。我一直安慰自己吵取,他們只是感情好禽额,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布锯厢。 她就那樣靜靜地躺著袍辞,像睡著了一般腕铸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上买雾,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天藻丢,我揣著相機與錄音剪撬,去河邊找鬼。 笑死悠反,一個胖子當著我的面吹牛残黑,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播斋否,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼梨水,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了茵臭?” 一聲冷哼從身側(cè)響起疫诽,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎旦委,沒想到半個月后奇徒,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡缨硝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年摩钙,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片查辩。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡胖笛,死狀恐怖奕短,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情匀钧,我是刑警寧澤翎碑,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站之斯,受9級特大地震影響日杈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜佑刷,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一莉擒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瘫絮,春花似錦涨冀、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至壮莹,卻和暖如春翅帜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背命满。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工涝滴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胶台。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓歼疮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親诈唬。 傳聞我的和親對象是個殘疾皇子韩脏,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容