中介者模式
中介者模式很好的诠释了迪米特法则,任意两个不相关的对象之间如果需要关联,那么需要通过第三个类来进行。中介者就是把一组对象进行封装,屏蔽了类之间的交互细节,使不同的类直接不需要持有对方引用也可以进行访问。
中介者Mediator会持有同事类(就是需要处理交互逻辑的对象)Colleague的引用,同时每个colleague也会持有Mediator一份引用。这样colleague如果有任何和别的类交互的请求就会发给Mediator,对改组对象进行了解耦合。其实我们平时经常写的视图控制器本身就是一个中介中,它来控制着不同对象之间的交互行为。
应用场景
对象间交互虽然定义明确然而非常复杂,导致一组对象彼此相互依赖而且难以理解;
因为对象引用了许多其他对象并与其通讯,导致对象难以复用;
想要定制一个分布在多个类中的逻辑或行为,又不想生成太多子类。
中介者的优缺点
优点
Mediator出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator,由于把对象如何写作进行了抽象,将中介者作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上,也就是站在一个更宏观的角度去看待系统。
缺点
由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
Demo
Colleague
#import <Foundation/Foundation.h> @class Mediator; @interface Colleague : NSObject @property (nonatomic, weak) Mediator* mediator; -(instancetype)initWithMediator:(Mediator *)mediator; -(void)notifyAnother; -(void)notified:(NSString *)message; @end #import "Colleague.h" #import "Mediator.h" @implementation Colleague -(instancetype)initWithMediator:(Mediator *)mediator { self = [super init]; if(self) { _mediator = mediator; } return self; } -(void)notified:(NSString *)message { NSLog(@"%@",message); } -(void)notifyAnother { [self.mediator notify:self]; } @end #import "Colleague.h" @interface ConcreteColleagueA : Colleague @end #import "ConcreteColleagueA.h" @implementation ConcreteColleagueA @end #import "Colleague.h" @interface ConcreteColleagueB : Colleague @end #import "ConcreteColleagueB.h" @implementation ConcreteColleagueB @end
在OC中为了避免引用循环,所以Colleague的Mediator对象修饰符用weak
Mediator
#import <Foundation/Foundation.h> #import "ConcreteColleagueA.h" #import "ConcreteColleagueB.h" @interface Mediator : NSObject @property (nonatomic ,strong) ConcreteColleagueA *colleagueA; @property (nonatomic ,strong) ConcreteColleagueB *colleagueB; -(void)notify:(NSObject *)obj; @end #import "Mediator.h" @implementation Mediator -(id)init { self = [super init]; if(self) { } return self; } -(void)notify:(NSObject *)obj { if (obj == self.colleagueA) { [self.colleagueB notified:@"B notified"]; } else { [self.colleagueA notified:@"A notified"]; } } @end
客户端
Mediator *mediator = [[Mediator alloc] init]; ConcreteColleagueA *colleagueA = [[ConcreteColleagueA alloc] initWithMediator:mediator]; ConcreteColleagueB *colleagueB = [[ConcreteColleagueB alloc] initWithMediator:mediator]; mediator.colleagueA = colleagueA; mediator.colleagueB = colleagueB; [colleagueA notifyAnother]; [colleagueB notifyAnother];
2015-07-26 16:48:42.508 Mediator[3888:1799182] B notified 2015-07-26 16:48:42.509 Mediator[3888:1799182] A notified
时间: 2024-11-09 06:42:49