外观模式
外观模式:为子系统中的一组接口提供一个统一的入口。外观模式定义 了一个高层接口,这个接口使得这一子系统更加容易使用,外观模式又称为门面模式,它是一种对象结构型模式。外观模式是迪米特法则的一种具体实 现,通过引入一个新的外观角色可以降低原有系统的复杂度,同时降低客户类与子系统的耦合度
//子系统 文件读
public class FileReader {
public String read(String fileNameSrc){
System.out.println("读取文件,获取文件:");
StringBuilder sb = new StringBuilder();
FileInputStream fs =null;
try {
fs = new FileInputStream(fileNameSrc);
int data;
while ((data = fs.read())!=-1){
sb=sb.append((char)data);
}
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件操作错误");
}finally {
try {
if(fs!=null){
fs.close();
}
} catch (IOException e) {
System.out.println("流关闭异常");
}
}
String string = sb.toString();
System.out.println(string);
return string;
}
}
//子系统 文件写入
public class FileWriter {
public void write(String encryptStr,String fileNameDes){
System.out.println("保存密文,写入文件:");
FileOutputStream fs=null;
try {
fs= new FileOutputStream(fileNameDes);
fs.write(encryptStr.getBytes());
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件存入失败");
}finally {
if (fs!=null){
try {
fs.close();
} catch (IOException e) {
System.out.println("流关闭失败");
}
}
}
}
}
//子系统 加密作用
public class NewCipher {
public String Encrypt(String plainText){
System.out.println("数据加密,将明文转换为密文:");
return Base64.getEncoder().encode(plainText.getBytes()).toString();
}
}
//外观角色
public class EncryptFacade {
private FileReader reader;
private NewCipher cipher;
private FileWriter fileWriter;
public EncryptFacade() {
this.reader = new FileReader();
this.cipher = new NewCipher();
this.fileWriter = new FileWriter();
}
public void FileEncrypt(String fileNameSrc,String fileNameDes){
String read = reader.read(fileNameSrc);
String encrypt = cipherMarchine.Encrypt(read);
fileWriter.write(encrypt,fileNameDes);
}
}
//client
public class FacadeClient {
public static void main(String[] args) {
AbsEncryptFacade encryptFacade = new EncryptFacadeA();
encryptFacade.FileEncrypt("tim.txt","test.txt");
}
}
优点
-
它对客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起 来更加容易。通过引入外观模式,客户端代码将变得很简单,与之关联的对象也很少
-
它实现了子系统与客户端之间的松耦合关系,这使得子系统的变化不会影响到调用它的客 户端,只需要调整外观类即可
-
一个子系统的修改对其他子系统没有任何影响,而且子系统内部变化也不会影响到外观对 象
缺点
-
不能很好地限制客户端直接使用子系统类,如果对客户端访问子系统类做太多的限制则减 少了可变性和灵活 性
-
如果设计不当,增加新的子系统可能需要修改外观类的源代码,违背了开闭原则
使用场景
-
当要为访问一系列复杂的子系统提供一个简单入口时可以使用外观模式
-
客户端程序与多个子系统之间存在很大的依赖性。引入外观类可以将子系统与客户端解耦,从而提高子系统的独立性和可移植性
-
在层次化结构中,可以使用外观模式定义系统中每一层的入口,层与层之间不直接产生联 系,而通过外观类建立联系,降低层之间的耦合度