定义:
将抽象部分与它的实现部分分离,使他们都可以独立变化.
实例:
手机都有各自的不同之处,但是他们都有一个手机卡槽,卡可以选择不同的运营商.不管手机和卡内部如何变化,只要卡槽的行业额标准不变, 就都可以正常的使用.桥接模式在于将复杂类进行分割,优先对象组合的方式.手机里的手机卡抽去新建一类,手机持有手机卡实例的组合.而不是通过集成来新建多个不同手机卡的手机子类.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @protocol SIMCardProtocal <NSObject>
- (void)getSIMInfo;
@end
@interface SIMCard : NSObject
- (void)getSIMInfo;
@end
@implementation SIMCard
- (void)getSIMInfo{}
@end
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| @interface UnicomSIMCard : SIMCard
@end
@imiplementation UnicomSIMCard
- (void)getSIMInfo { NSLog(@"欢迎使用联通卡"); }
@end
@interface MobileSIMCard : SIMCard<SIMCardProtocol>
@end
@implementation MobileSIMCard
- (void)getSIMInfo { NSLog(@"欢迎使用移动"); }
@end
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @interface Phone : NSObject
@property (nonatomic, strong) SIMCard *simCard;
- (void)launchPhone;
@end
@implementation Phone
- (void)launchPhone { if (self.simCard) { [self.simCard getSIMInfo]; } }
@end
|
1 2 3 4 5 6 7 8 9
| @interface iPhone : Phone
@end
@interface miPhone : Phone
@end
|
1 2 3 4 5 6 7 8 9 10 11 12
| UnicomSIMCard *unicomSim = [UnicomSimCard new]; MobileSIMCard *mobileSim = [MobileSIMCard new];
miPhone *mi = [miPhone new]; [mi setSimCard:unicomCard];
iPhone *iphone = [iPhone new]; [iphone setSimCard:mobileSim];
[mi launchPhone]; [iphone launchPhone];
|
优点:
缺点: