中介者模式

定义

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

场景

  • 系统中对象之间存在比较复杂的引用关系
  • 想通过一个中间类来封装多个类的行为,而又不想生成太多的子类

实现

以AColleague与BColleague简单发消息为例。
1、UML图


中介者模式.png

2、使用

  • 构建抽象中介者及抽象角色
@interface Colleague : NSObject
@property(nonatomic, copy)NSString *name;
@property(nonatomic, strong)Mediator *mediator;
-(instancetype)initWithName:(NSString*)name;
-(void)sendMsg:(NSString*)msg;
-(void)notify:(NSString*)msg;
@end
#import "Colleague.h"

@implementation Colleague
- (instancetype)initWithName:(NSString *)name
{
    self = [super init];
    if (self) {
        self.name = name;
    }
    return self;
}
-(void)sendMsg:(NSString*)msg{
    NSLog(@"由具体的子类实现");
}

- (void)notify:(NSString *)msg{
    NSLog(@"%@ 收到消息:%@", self.name, msg);
}
@end
@class  Colleague;
@interface Mediator : NSObject
-(void)sendMsg:(NSString*)msg colleague:(Colleague*)colleague;;
@end
#import "Mediator.h"

@implementation Mediator
- (void)sendMsg:(NSString *)msg colleague:(Colleague *)colleague{
    NSLog(@"由子类具体实现");
}
@end
  • 构建具体中介者及具体角色
@interface ConcretMediator : Mediator
@property(nonatomic,strong)AColleague *aColleague;
@property(nonatomic, strong)BColleague *bColleague;
@end
#import "ConcretMediator.h"

@implementation ConcretMediator
- (void)sendMsg:(NSString *)msg colleague:(Colleague *)colleague{
    if(colleague == self.aColleague){
        [self.bColleague notify:msg];
    }else{
        [self.aColleague notify:msg];
    }
}
@end

@interface AColleague : Colleague

@end
#import "AColleague.h"

@implementation AColleague
- (void)sendMsg:(NSString *)msg{
    [self.mediator sendMsg:msg colleague:self];
}
@end

@interface BColleague : Colleague

@end
#import "BColleague.h"

@implementation BColleague
- (void)sendMsg:(NSString *)msg{
    [self.mediator sendMsg:msg colleague:self];
}
@end

总结

减少类间依赖,减低了耦合,符合迪米特法则。

代码

链接: https://pan.baidu.com/s/1XKd0siIwoQtJQBPVl3H7qQ 提取码: hh1r

你可能感兴趣的:(中介者模式)