設計模式 —— 中介模式(解藕)

設計模式 —— 中介模式

原理:用一箇中介對象來封裝一系列的對象交互,中介者使各對象不需要顯示的相互引用,從而使其耦合度降低,而且可以獨立的改變他們之間的交互 (將網狀結構轉換爲線型結構,減少耦合)

解決的問題:將網狀結構轉換爲線型結構,減少耦合;增加可維護性;降低複雜度;

使用方法:

可用代理——繼承方法
委託方創建協議;
創建父類中介類,並遵守協議;
在子類中實現不同的功能

1、委託方定協議(父類)

.h
#import <Foundation/Foundation.h>
@class AbstructCollege;

@protocol CollegeDelegate <NSObject>
@optional//可選擇
- (void)collegeEvent:(AbstructCollege *)college;
@end

@interface AbstructCollege : NSObject
@property (nonatomic,weak) id <CollegeDelegate> delegate;
@end


.m
#import "AbstructCollege.h"

@implementation AbstructCollege
@end

2、中介器(父類)

.h
//遵守協議
#import <Foundation/Foundation.h>
#import "AbstructCollege.h"

@interface AbstructMediort : NSObject <CollegeDelegate>
@end


.m
//實現代理
#import "AbstructMediort.h"

@implementation AbstructMediort
- (void)collegeEvent:(AbstructCollege *)college {
    
}
@end

3、委託方子類對象

.h
#import <UIKit/UIKit.h>
#import "AbstructCollege.h"

@interface College : AbstructCollege
@property (nonatomic,assign) CGFloat value;
- (void)changeValue:(CGFloat)value;
@end

.m
#import "College.h"

@implementation College
- (void)changeValue:(CGFloat)value {
    self.value = value;
    if (self.delegate && [self.delegate respondsToSelector:@selector(collegeEvent:)]){
        [self.delegate collegeEvent:self];
    }
}
@end

4、中介器子類1(如果規則有改變可以再創建對應的子類中介器)

.h
#import "AbstructMediort.h"
#import "College.h"

@interface TypeOneMediator : AbstructMediort
@property (nonatomic,strong) College *colleagueA;
@property (nonatomic,strong) College *colleagueB;
@property (nonatomic,strong) College *colleagueC;
- (NSDictionary *)values;//查看打印信息
@end

.m
#import "TypeOneMediator.h"

@implementation TypeOneMediator

- (void)collegeEvent:(AbstructCollege *)college {
    if ([college isEqual:self.colleagueA]) {
        self.colleagueB.value = self.colleagueA.value * 2;
        self.colleagueC.value = self.colleagueA.value * 4;
    } else if ([college isEqual:self.colleagueB]) {
        self.colleagueA.value = self.colleagueB.value / 2;
        self.colleagueC.value = self.colleagueB.value * 2;
    } else {
        self.colleagueA.value = self.colleagueC.value / 4;
        self.colleagueB.value = self.colleagueC.value / 2;
    }
}

- (NSDictionary *)values {
    return @{@"A":@(self.colleagueA.value),
             @"B":@(self.colleagueB.value),
             @"C":@(self.colleagueC.value),
             };
}

5、調用時不必處理對象間的複雜邏輯判斷,直接交給中介器處理

self.typeOne = [[TypeTwoMediator alloc] init];
    
College *colleagueA = [[College alloc] init];
College *colleagueB = [[College alloc] init];
College *colleagueC = [[College alloc] init];
    
self.typeOne.colleagueA = colleagueA;
self.typeOne.colleagueB = colleagueB;
self.typeOne.colleagueC = colleagueC;
    
colleagueA.delegate = self.typeOne;
colleagueB.delegate = self.typeOne;
colleagueC.delegate = self.typeOne;
    
[colleagueA changeValue:4];
NSLog(@"%@",self.typeOne.values);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章