桥接模式
桥接模式(Bridge Pattern)的用意是将抽象化与实现化解耦,使得二者可以独立变化。
Abstraction表示抽象类 它定义了抽象类的接口,并且维护一个抽象实现类Implementor的对象;
RefineAbstratction表示扩充的抽象类,它扩充由Abstratcion定义的接口;
Implementor表示抽象实现类接口用于定义类的接口,这个接口不一定要与abstraction的接口完全一致,事实上着两个接口定义可以完全不同
桥接模式之跨平台视频播放器
1:实例说明:
开发一个跨平台的视频播放器,可以在不同的操作系统平台(Windows ,Linux)上播放多种格式的视频文件,如MPEG,RMVB,AVIWMV等等。
实例类图:
Abstraction:
抽象类OperationSystemVersion
package Abstraction;
import Implementor.VideoFile;
public abstract class OperationSystemVersion {
protected VideoFile vf;
public void setVideoFile(VideoFile vf){
this.vf=vf;
}
public abstract void play(String fileName);
}
RefinedAbstraction:
LinuxVersion:
package RefinedAbstraction;
import Abstraction.OperationSystemVersion;
public class LinuxVersion extends OperationSystemVersion {
@Override
public void play(String fileName) {
vf.decode("Linux",fileName);
}
}
UnixVersion
package RefinedAbstraction;
import Abstraction.OperationSystemVersion;
public class UnixVersion extends OperationSystemVersion {
@Override
public void play(String fileName) {
vf.decode("Unix",fileName);
}
}
WindowsVersion
package RefinedAbstraction;
import Abstraction.OperationSystemVersion;
public class WindowsVersion extends OperationSystemVersion {
@Override
public void play(String fileName) {
vf.decode("Windows",fileName);
}
}
Implementor
VideoFile
package Implementor;
public interface VideoFile {
public void decode(String osType,String fileName);
}
ConcreteImplements:
AVIFile
package ConcreteImplements;
import Implementor.VideoFile;
public class AVIFile implements VideoFile {
@Override
public void decode(String osType, String fileName) {
System.out.println("格式为AVI的视频文件:"+fileName+"在"+osType+"平台中解码播放");
}
}
MPEGFile
package ConcreteImplements;
import Implementor.VideoFile;
public class MPEGFile implements VideoFile {
@Override
public void decode(String osType, String fileName) {
System.out.println("格式为MPEG的视频文件:"+fileName+"在"+osType+"平台中解码播放");
}
}
RMVBFile
package ConcreteImplements;
import Implementor.VideoFile;
public class RMVBFile implements VideoFile {
@Override
public void decode(String osType, String fileName) {
System.out.println("格式为RMVB的视频文件:"+fileName+"在"+osType+"平台中解码播放");
}
}
WMVFile
package ConcreteImplements;
import Implementor.VideoFile;
public class WMVFile implements VideoFile {
@Override
public void decode(String osType, String fileName) {
System.out.println("格式为AVI的视频文件:"+fileName+"在"+osType+"平台中解码播放");
}
}
Test
package Test;
import Abstraction.OperationSystemVersion;
import ConcreteImplements.AVIFile;
import Implementor.VideoFile;
import RefinedAbstraction.UnixVersion;
public class test {
public static void main(String args[]){
VideoFile file;
OperationSystemVersion version;
file=new AVIFile();
version=new UnixVersion();
version.setVideoFile(file);
version.play("《三毛流浪记》");
}
}
测试结果: