定义
桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
原理
抽象层与实现层相分离,抽象层定义了供客户端调用的抽象接口,实现层提供了具体的逻辑,实现类的引用被封装到抽象层的实例中,桥接就形成.
代码分析
- Remote抽象类
#import <Foundation/Foundation.h>#import "TV.h"@interface Remote : NSObject@property (nonatomic,strong)TV *tv;-(void)setCommand:(NSString *)command;@end#import "Remote.h"@implementation Remote- (void)setCommand:(NSString *)command{//桥接的形成[self.tv loadCommand:command];}@end
- SubRemote类,继承Remote类
#import "Remote.h"@interface SubRemote : Remote- (void)up;- (void)down;- (void)left;- (void)right;@end#import "SubRemote.h"@implementation SubRemote- (void)up{[super setCommand:@"up"];}- (void)down{[super setCommand:@"down"];}- (void)left{[super setCommand:@"left"];}- (void)right{[super setCommand:@"right"];}@end
- TV类,抽象类
#import <Foundation/Foundation.h>@interface TV : NSObject- (void)loadCommand:(NSString *)command;@end#import "TV.h"@implementation TV//抽象方法- (void)loadCommand:(NSString *)command{//无需实现}@end
- XiaoMiTV类,继承TV
#import "TV.h"@interface XiaoMiTV : TV@end#import "XiaoMiTV.h"@implementation XiaoMiTV- (void)loadCommand:(NSString *)command{if ([command isEqualToString:@"up"]) {NSLog(@"你按的是xiaoMi====:%@",command);}else if ([command isEqualToString:@"down"]) {NSLog(@"您按的是XM:----%@",command);}else if ([command isEqualToString:@"left"]) {NSLog(@"您按的是XM:----%@",command);}else if ([command isEqualToString:@"right"]) {NSLog(@"您按的是XM:----%@",command);}else {NSLog(@"超出范围");}}@end
- HaiXinTV类,继承TV
#import "TV.h"@interface HaiXinTV : TV@end#import "HaiXinTV.h"@implementation HaiXinTV- (void)loadCommand:(NSString *)command{if ([command isEqualToString:@"up"]) {NSLog(@"你按的是HaiXin====:%@",command);}else if ([command isEqualToString:@"down"]) {NSLog(@"您按的是HaiXin:----%@",command);}else if ([command isEqualToString:@"left"]) {NSLog(@"您按的是HaiXin:----%@",command);}else if ([command isEqualToString:@"right"]) {NSLog(@"您按的是HaiXin:----%@",command);}else {NSLog(@"超出范围");}}@end
- VC类
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@end#import "ViewController.h"#import "SubRemote.h"#import "XiaoMiTV.h"#import "HaiXinTV.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];SubRemote *subRemote = [[SubRemote alloc] init];XiaoMiTV *xmTV = [[XiaoMiTV alloc] init];subRemote.tv = xmTV;[subRemote up];[subRemote down];HaiXinTV *hxTV = [[HaiXinTV alloc] init];subRemote.tv = hxTV;[subRemote up];[subRemote down];}@end

