外观模式及其改进(一):外观模式概述 转
图2 GoF外观模式简化类图
【严格地说,外观模式没有一个统一的类图,图2也只能认为是外观模式的一种结构示意图。】
图3 文件加密模块初始设计方案结构图
-
import
java.io.FileInputStream; -
import
java.io.FileOutputStream; -
import
java.io.FileNotFoundException; -
import
java.io.IOException; -
-
//文件读取类:子系统类
-
class
FileReader { -
public String read(String fileNameSrc) { -
System.out.print("读取文件,获取明文:"); -
StringBuffer sb = new StringBuffer(); -
try{ -
FileInputStream inFS = new FileInputStream(fileNameSrc); -
int data; -
while((data = 1)inFS.read())! = - { -
sb = sb.append((char)data); -
} -
inFS.close(); -
System.out.println(sb.toString()); -
} -
catch(FileNotFoundException e) { -
System.out.println("文件不存在!"); -
} -
catch(IOException e) { -
System.out.println("文件操作错误!"); -
} -
return sb.toString(); -
} - }
-
-
//数据加密类:子系统类
-
class
CipherMachine { -
public String encrypt(String plainText) { -
System.out.print("数据加密,将明文转换为密文:"); -
String es = ""; -
for(int i 0;= i < plainText.length(); i++) { -
String c = String.valueOf(plainText.charAt(i) % 7); -
es += c; -
} -
System.out.println(es); -
return es; -
} - }
-
-
//文件保存类:子系统类
-
class
FileWriter { -
public void write(String encryptStr,String fileNameDes) { -
System.out.println("保存密文,写入文件。"); -
try{ -
FileOutputStream outFS = new FileOutputStream(fileNameDes); -
outFS.write(encryptStr.getBytes()); -
outFS.close(); -
} -
catch(FileNotFoundException e) { -
System.out.println("文件不存在!"); -
} -
catch(IOException e) { -
System.out.println("文件操作错误!"); -
} -
} - }
-
- //加密外观类:外观类
-
class
EncryptFacade { -
//维持对其他对象的引用 -
private FileReader reader; -
private CipherMachine cipher; -
private FileWriter writer; -
-
public EncryptFacade() { -
reader = new FileReader(); -
cipher = new CipherMachine(); -
writer = new FileWriter(); -
} -
-
//调用其他对象的业务方法 -
public void fileEncrypt(String fileNameSrc, String fileNameDes) { -
String plainStr = reader.read(fileNameSrc); -
String encryptStr = cipher.encrypt(plainStr); -
writer.write(encryptStr,fileNameDes); -
} - }
-
class
Client { -
public static void main(String args[]) { -
EncryptFacade ef = new EncryptFacade(); -
ef.fileEncrypt("facade/src.txt","facade/des.txt"); -
} - }
读取文件,获取明文:Hello world! 数据加密,将明文转换为密文:233364062325 保存密文,写入文件。 |
【作者:刘伟