外观模式
文章目录
定义:要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。外观模式提供了一个高层次的接口,使得子系统更易于使用。
简单来说就是外观模式能为程序库、 框架或其他复杂类提供一个简单的接口,客户端仅通过这个接口与子系统进行交互。
代码实现:
子系统代码
@Data
@AllArgsConstructor
public class VideoFile {
private String name;
private Codec codec;
public VideoFile(String name) {
this.name = name;
this.codec = CodecFactory.getCodec(name.substring(name.indexOf(".") + 1));
}
public File toFile() {
return new File(this.name);
}
}
public interface Codec{}
public class FLVCodec implements Codec{}
public class MP4Codec implements Codec{}
public class CodecFactory {
public static Codec getCodec(String format){
if(format=="mp4"){
return new MP4Codec();
}else if(format=="flv"){
return new FLVCodec();
}
return null;
}
public static VideoFile convert(VideoFile source,Codec codec){
return new VideoFile(source.getName(),codec);
}
}
外观类 :
public class VideoConversionFacade {
public File convertVideo(String sourceFileName,String format){
// 客户端通过外观类与子类交互
VideoFile source=new VideoFile(sourceFileName);
Codec dstCodec = CodecFactory.getCodec(format);
VideoFile result=CodecFactory.convert(source,dstCodec);
return result.toFile();
}
}
VideoConversionFacade facade = new VideoConversionFacade();
facade.convertVideo("11.flv", "mp4");
外观模式的优点是将客户端与复杂子系统解耦,客户端不需要了解子系统内部的实现,使得子系统本身可以独立变化。 缺点是可能使得外观类成为与子系统中所有类都耦合的上帝对象。
文章作者 梧桐碎梦
上次更新 2023-04-29 10:08:31