首页 技术 正文
技术 2022年11月8日
0 收藏 869 点赞 1,503 浏览 1865 个字

桥接模式

桥接模式就是让抽象和实现分离的最好体现,符合面向对象的依赖倒转原则。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
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289