- 介绍
外观模式实现了通过访问外观类的简单接口就可以操作系统,用户不必与复杂的子系统进行交互。本质就是类的封装。
为实现代码的重用性,将加密操作分为三个代码块,读取FileReader、加密CipherMachine、保存FileWriter。将某一文件的内容读取出来后,内容进行加密,并将加密的新内容保存到另外一个文件中。
- 类图
- 代码
public class FileReader { public String read(String path){ FileInputStream fis=null; try { fis=new FileInputStream(path); byte[]b=new byte[1024]; int len=0; StringBuffer sb=new StringBuffer(); while((len=fis.read(b))!=-1){ sb.append(new String(b,0,len)); } return sb.toString(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { try { fis.close(); }catch (IOException e){ e.printStackTrace(); } } return ""; } } public class FileWriter { public void write(String content,String path){ FileOutputStream fos=null; try { fos=new FileOutputStream(path); fos.write(content.getBytes()); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } finally { try { fos.close(); }catch (IOException e){ e.printStackTrace(); } } } } public class CipherMachine { public String Encrypt(String str){ char[]arr=str.toCharArray(); StringBuffer sb=new StringBuffer(); for (char c: arr) { sb.append(c+1); } return sb.toString(); } } public class EncryptFacade { private FileReader fileReader; private CipherMachine cipherMachine; private FileWriter fileWriter; public EncryptFacade(){ fileReader=new FileReader(); cipherMachine=new CipherMachine(); fileWriter=new FileWriter(); } public void FileEncrypt(String source,String target){ String str=fileReader.read(source); String enStr=cipherMachine.Encrypt(str); fileWriter.write(enStr,target); } } public class Main { public static void main(String[] args) { EncryptFacade encryptFacade=new EncryptFacade(); encryptFacade.FileEncrypt("D:\\facade\\source.txt","D:\\facade\\target.txt"); } }