1.概念
- 桥接模式是一种很实用的结构型设计模式,如果软件系统中某个类存在两个独立变化的维 度,通过该模式可以将这两个维度分离出来,使两者可以独立扩展,让系统更加符合“单一职 责原则”。与多层继承方案不同,它将两个独立变化的维度设计为两个独立的继承等级结构, 并且在抽象层建立一个抽象关联,该关联关系类似一条连接两个独立继承结构的桥,故名桥 接模式。
- 桥接模式用一种巧妙的方式处理多层继承存在的问题,用抽象关联取代了传统的多层继承, 将类之间的静态继承关系转换为动态的对象组合关系,使得系统更加灵活,并易于扩展,同 时有效控制了系统中类的个数。
2.UML图![在这里插入图片描述](https://img-blog.csdnimg.cn/20200417221530486.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUyMDQ2,size_16,color_FFFFFF,t_70#pic_center)
3.代码展示
//客户端
public class Client {
public static void main(String a[]){
VideoFile vf;
OperatingSystemVersion osType1;
osType1 =new WindowsVersion();
vf = new RMVBFile();
osType1.setVideoFile(vf);
osType1.display("水浒传");
OperatingSystemVersion osType2;
osType2 =new LinuxVersion();
vf = new AVIFile();
osType2.setVideoFile(vf);
osType2.display("西游记");
OperatingSystemVersion osType3;
osType3 =new UnixVersion();
vf = new WMVFile();
osType3.setVideoFile(vf);
osType3.display("红楼梦");
OperatingSystemVersion osType4;
osType4 =new LinuxVersion();
vf = new MPEGFile();
osType4.setVideoFile(vf);
osType4.display("三国演义");
}
}
//抽象视频文件实现类:实现类接口
interface VideoFile{
public void docode(String osType ,String fileName);
}
//MPEG文件实现类:具体实现类
class MPEGFile implements VideoFile{
public void docode(String osType ,String fileName){
System.out.println(osType+"正在以MPEG格式播放:"+fileName);
}
}
//RMVB文件实现类:具体实现类
class RMVBFile implements VideoFile{
public void docode(String osType ,String fileName){
System.out.println(osType+"正在以RMVB格式播放:"+fileName);
}
}
//AVI文件实现类:具体实现类
class AVIFile implements VideoFile{
public void docode(String osType ,String fileName){
System.out.println(osType+"正在以AVI格式播放:"+fileName);
}
}
//WMV文件实现类:具体实现类
class WMVFile implements VideoFile{
public void docode(String osType ,String fileName){
System.out.println(osType+"正在以WMV格式播放:"+fileName);
}
}
//抽象操作系统类:抽象类
abstract class OperatingSystemVersion{
protected VideoFile vf;
//protected VideoFile vf=new AVIFile();
public void setVideoFile(VideoFile vf) {
this.vf = vf;
}
public abstract void display(String fileName);
}
//Windows操作系统类:扩充抽象类
class WindowsVersion extends OperatingSystemVersion{
public void display(String fileName){
String osType = "Windows";
vf.docode(osType, fileName);
//System.out.println("正在"+osType+"以"+fileName+"格式播放:");
}
}
//Linux操作系统类:扩充抽象类
class LinuxVersion extends OperatingSystemVersion{
public void display(String fileName){
String osType = "Linux";
vf.docode(osType, fileName);
//System.out.println("正在"+osType+"以"+fileName+"格式播放:");
}
}
//Unix操作系统类:扩充抽象类
class UnixVersion extends OperatingSystemVersion{
public void display(String fileName){
String osType = "Unix";
vf.docode(osType, fileName);
//System.out.println("正在"+osType+"以"+fileName+"格式播放:");
}
}
4.结果展示
5.总结分析
1.优点
(1).分离抽象接口及实现部分,桥接模式是比多继承更好的解决办法。
(2).桥接模式提高的系统的可扩展性,对变化的维度进行扩展,而不需要修改原有的系统。
(3).实现细节对客户透明,可以对用户隐藏实现细节。
2.缺点
(1).桥接模式增加了系统的理解和设计难度,要求设计人员对抽象进行设计和编码,桥接模式要求系统识别两个独立变化的维度,适用范围具有一定的局限性。