行为型之五-中介者模式

Mediator(中介者模式)

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

VC.m

///根据迪米特原则,两个不相关的对象不应该直接通讯。世界各国都通过联合国这个中介者来处理纠纷利益等。
//初始化一个中介者对象
ConcreteMediator *mediator = [[ConcreteMediator alloc]init];
//初始化并且让两个同事有相同的中介者对象
ConcreteColleague1 *c1 = [[ConcreteColleague1 alloc]initWithMediator:mediator];
ConcreteColleague2 *c2 = [[ConcreteColleague2 alloc]initWithMediator:mediator];
//给中介者对象绑定两个要交互的同事对象
mediator.colleague1 = c1;
mediator.colleague2 = c2;
//c1和c2都通过mediator发送信息
[c1 send:@"吃过饭了吗?"];
[c2 send:@"没有呢,你打算请客?"];

// 中介
Mediator.h

@interface Mediator : NSObject
@property(nonatomic, strong)Colleague *colleague1;
@property(nonatomic, strong)Colleague *colleague2;
-(void)send:(NSString *)message colleague:(Colleague *)colleague;
@end

ConcreteMediator.m

@implementation ConcreteMediator
@synthesize colleague1 =_colleague1;
@synthesize colleague2 = _colleague2;
-(void)send:(NSString *)message colleague:(Colleague *)colleague{
    if (colleague == _colleague1) {
        [_colleague2 notify:message];
    }else{
        [_colleague1 notify:message];
    }
}
@end

// 对象
Colleague.h

@interface Colleague : NSObject
@property(nonatomic, strong)Mediator *mediator;
-(instancetype)initWithMediator:(Mediator *)mediator;
-(void)notify:(NSString *)message;
-(void)send:(NSString *)message;
@end

ConcreteColleague1.m

@implementation ConcreteColleague1
@synthesize mediator = _mediator;
-(instancetype)initWithMediator:(Mediator *)mediator{
    self = [super init];
    if (self) {
        _mediator = mediator;
    }
    return self;
}
-(void)send:(NSString *)message{
    NSLog(@"同事1发送了信息");
    [_mediator send:message colleague:self];
}
-(void)notify:(NSString *)message{
    NSLog(@"%@%@",@"同事1得到消息:", message);
}
@end

设计图

行为型之五-中介者模式_第1张图片

你可能感兴趣的:(行为型之五-中介者模式)