参考《设计模式的艺术软件开发人员内功修炼之道》-刘伟 著
实验目的
外观模式作为调用者和系统之间的接口,屏蔽了系统的具体细节,简化调用
实验代码
package Facade;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class ReadFile {
public static String readFile(String filename) throws IOException {
File file = new File(filename);
if (!(file.exists() && file.canRead() && file.isFile())) {
System.out.println("source file not satisfy requirement");
return null;
}
StringBuffer sb = new StringBuffer();
FileInputStream is = new FileInputStream(filename);
int data;
while ((data = is.read()) != -1) {
sb.append((char) data);
}
System.out.println("return string of readFile is " + sb.toString());
return sb.toString();
}
}
class EncryFile {
public static String encryFile(String str) {
StringBuffer sb = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; i++) {
char c = (char) (str.charAt(i) + 0);
sb.append(c);
}
System.out.println("return string of encryFile is " + sb.toString());
return sb.toString();
}
}
class WriteFile {
public static void writeFile(String encryContent, String filename) throws IOException {
File file = new File(filename);
if (file.exists() && !file.canWrite()) {
System.out.println("dest file not satisfy requirement");
return;
}
if (!file.exists())
file.createNewFile();
FileOutputStream os = new FileOutputStream(filename);
os.write(encryContent.getBytes());
System.out.println("return string of writeFile is " + encryContent);
}
}
interface AbstractInterface {
public void encryptFile(String filesrc, String filedest) throws IOException;
}
class ConcreteImpletation implements AbstractInterface {
@Override
public void encryptFile(String filesrc, String filedest) throws IOException {
// TODO Auto-generated method stub
String content = ReadFile.readFile(filesrc);
String encryContent = EncryFile.encryFile(content);
WriteFile.writeFile(encryContent, filedest);
}
}
public class FacadeTest {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
AbstractInterface intf = new ConcreteImpletation();
intf.encryptFile("D:/src.txt", "D:/dest.txt");
return;
}
}
结果输出
return string of readFile is abcdefg
hijklmn
return string of encryFile is abcdefg
hijklmn
return string of writeFile is abcdefg
hijklmn
结论
- 外观模式解耦客户端和系统,减少复杂依赖关系
- 改变接口只需要增加具体的外观实现类即可