设计模式2-中介者模式

问题:

在软件的开发过程中,势必会碰到这样一种情况,多个类或多个子系统相互交互,而且交互很繁琐,导致每个类都必须知道他需要交互的类,这样它们的耦合会显得异常厉害。牵一发而动全身,
好了,既然问题提出来了,那有请我们这期的主角——中介者模式出场吧!

中介者模式

用一个中介者对象来封装一系列的对象交互。中介者使得各对象不需要显式地相互引用,从而使其松散耦合,而且可以独立地改变它们之间的交互。

中介者模式结构图

例子(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<<"下面的班长发布一个通知的场景:"<<endl;
    //将同学们加入到qq群中
    qq.addStudent(&studentMonitor);
    qq.addStudent(&studentTuanZhiShu);
    qq.addStudent(&studentA);
    qq.addStudent(&studentB);
    //设置大家的回复消息
    studentMonitor.setContent("明天下午2点开年纪会,收到回复");
    studentTuanZhiShu.setContent("知道了,肯定到");
    studentA.setContent("收到了,但是可能晚点到");
    studentB.setContent("收到了,但是明天考试");
    //开始发通知
    qq.notify(&studentMonitor);
    cout<<endl<<"下面是两个同学的私下交流"<<endl;
    studentMonitor.setContent("你觉得我们的老师怎么样");
    studentA.setContent("我觉得不好");
    qq.chart(&studentMonitor, &studentA);
}

下面的班长发布一个通知的场景:
大班长说:明天下午2点开年纪会,收到回复
团支书说:知道了,肯定到
学生A说:收到了,但是可能晚点到
同学B说:收到了,但是明天考试

下面是两个同学的私下交流
大班长说:你觉得我们的老师怎么样
学生A说:我觉得不好

总结:

中介者模式很容易在系统中应用,也很容易在系统中误用。当系统出现了多对多交互复杂的对象群时,不要急于使用中介者模式,而要先反思你在系统上设计是否合理。
优点就是集中控制,减少了对象之间的耦合度。缺点就是太过于集中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容