桥接模式
桥接模式就是让抽象和实现分离的最好体现,符合面向对象的依赖倒转原则。Abstruct抽象类负责设计客户端接口,Implementor则负责具体的细节逻辑。
在桥接模式中,Abstruct类持有一个Implementor类的引用,该引用也是桥接的两个对象的唯一通信点。
应用场景
1.不想在抽象与其实现之间形成固定的绑定关系(这样就能在运行时切换实现);
2.抽象及其实现都应该可以通过子类化独立进行扩展;
3.对抽象的实现进行修改不应该影响客户端代码;
4.如果每一个实现需要额外的子类以进行细化抽象,则说名有必要把它们分成两个部分;
5.如果每个实现需要额外的子类以细化抽象,则说明有必要把它们分成两个部分;
6.想在带有不同抽象接口的多个对象之间共享一个实现。
适配器与桥接
适配器和桥接可以说非常相似,都是包装一个类提供通用接口以适应客户端。
但是适配器都是在代码维护阶段或者非架构阶段用来修补的一种方式,也就是说如果现在有两个现成的模块要进行对接,但是想要修改两边的接口都比较困难,这时候就用适配器来辅助对接。
桥接一般是在架构阶段使用,使用桥接来分离抽象和实现,能够使细节得以复用,并且解耦合的一种方式。
Demo
Abstruct
#import <Foundation/Foundation.h>
#import "Implementor.h"
@interface Abstruct : NSObject-(void)sayName;
-(void)setImplementor:(Implementor *)newImplementor;@end#import "Abstruct.h"
#import "Implementor.h"@implementation AbstructImplementor *_implementor;-(void)setImplementor:(Implementor *)newImplementor{
_implementor = newImplementor;
}-(void)sayName{
[_implementor sayFirstName];
[_implementor sayLastName];
}@end
Implementor
#import <Foundation/Foundation.h>@interface Implementor : NSObject-(void)sayFirstName;
-(void)sayLastName;@end#import "Implementor.h"@implementation Implementor-(void)sayFirstName{
NSLog(@"%@",NSStringFromClass([self class]));
}-(void)sayLastName{
NSLog(@"%@",NSStringFromClass([self class]));
}@end#import <Foundation/Foundation.h>
#import "Implementor.h"
@interface ConcreateImplementorA : Implementor@end#import <Foundation/Foundation.h>
#import "Implementor.h"@interface ConcreateImplementorB : Implementor@end
ConcreateImplmentorA、B实现中没有写任何代码(偷懒了)
客户端
Abstruct *abstruct = [Abstruct new];
ConcreateImplementorA *implementA = [ConcreateImplementorA new];
ConcreateImplementorB *implementB = [ConcreateImplementorB new]; [abstruct setImplementor:implementA];
[abstruct sayName]; [abstruct setImplementor:implementB];
[abstruct sayName];
结果
-- ::10.215 Bridge[:] ConcreateImplementorA
-- ::10.217 Bridge[:] ConcreateImplementorA
-- ::10.217 Bridge[:] ConcreateImplementorB
-- ::10.217 Bridge[:] ConcreateImplementorB