橋接模式---把兩個(gè)相關(guān)聯(lián)的類抽象出來, 以達(dá)到解耦的目的
比如XBox遙控器跟XBox主機(jī), 我們抽象出主機(jī)和遙控器兩個(gè)抽象類, 讓這兩個(gè)抽象類耦合
然后生成這兩個(gè)抽象類的實(shí)例XBox & XBox主機(jī) 以達(dá)到解耦
同時(shí)還能再繼承為其他的游戲機(jī)
因?yàn)槭强刂破髟诳刂浦鳈C(jī), 所以控制器抽象類會(huì)持有主機(jī)抽象類
BaseControl.h
#import <Foundation/Foundation.h>
#import "BaseGameSystem.h"
@interface BaseControl : NSObject
@property (nonatomic, strong) BaseGameSystem *gameSystem;
/**
上下左右AB-方法
*/
- (void)up;
- (void)down;
- (void)left;
- (void)right;
- (void)commandA;
- (void)commandB;
@end
BaseControl.m
#import "BaseControl.h"
@implementation BaseControl
- (void)up {
[self.gameSystem loadComand:kUp];
}
- (void)down {
[self.gameSystem loadComand:kDown];
}
- (void)left {
[self.gameSystem loadComand:kLeft];
}
- (void)right {
[self.gameSystem loadComand:kRight];
}
- (void)commandA {
[self.gameSystem loadComand:kA];
}
- (void)commandB {
[self.gameSystem loadComand:kB];
}
@end
BaseGameSystem.h
#import <Foundation/Foundation.h>
typedef enum : NSUInteger {
kUp = 0x1,
kDown,
kLeft,
kRight,
kA,
kB,
kO,
kX
} EcomandType;
@interface BaseGameSystem : NSObject
/**
加載指令
@param type 指令代碼
*/
- (void)loadComand:(EcomandType) type;
@end
BaseGameSystem.m
#import "BaseGameSystem.h"
@implementation BaseGameSystem
- (void)loadComand:(EcomandType)type {
}
@end
這樣兩個(gè)抽象類就耦合了, 現(xiàn)在我們創(chuàng)建實(shí)例
XBoxGameSystem.h
#import "BaseGameSystem.h"
@interface XBoxGameSystem : BaseGameSystem
@end
XboxGameSystem.m
#import "XBoxGameSystem.h"
@implementation XBoxGameSystem
- (void)loadComand:(EcomandType)type {
switch (type) {
case kUp:
NSLog(@"UP");
break;
case kDown:
NSLog(@"Down");
break;
case kRight:
NSLog(@"Right");
break;
case kLeft:
NSLog(@"Left");
break;
case kA:
NSLog(@"kA");
break;
case kB:
NSLog(@"kB");
break;
default:
NSLog(@"None");
break;
}
}
@end
XBoxController.h
#import "BaseControl.h"
@interface XBoxController : BaseControl
@end
XBoxController.m
#import "XBoxController.h"
@implementation XBoxController
@end
下面是Controller中使用
#import "ViewController.h"
#import "BaseControl.h"
#import "XBoxGameSystem.h"
#import "XBoxController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
BaseControl *controller = [[XBoxController alloc] init];
controller.gameSystem = [[XBoxGameSystem alloc] init];
[controller up];
}
@end