深入浅出外观模式(二) 转
3. 外观模式应用实例
|
图4 文件加密模块结构图
-
//FileReader.cs
-
using
System; -
using
System.Text; -
using
System.IO; -
-
namespace
FacadeSample - {
-
class FileReader -
{ -
public string Read( stringfileNameSrc) -
{ -
Console.Write("读取文件,获取明文:"); -
FileStream fs = null; -
StringBuilder sb = new StringBuilder(); -
try -
{ -
fs = new FileStream(fileNameSrc, FileMode.Open); -
int data; -
while((data = fs.ReadByte())!= -1) -
{ -
sb = sb.Append((char)data); -
} -
fs.Close(); -
Console.WriteLine(sb.ToString()); -
} -
catch(FileNotFoundException e) -
{ -
Console.WriteLine("文件不存在!"); -
} -
catch(IOException e) -
{ -
Console.WriteLine("文件操作错误!"); -
} -
return sb.ToString(); -
} -
} - }
-
//CipherMachine.cs
-
using
System; -
using
System.Text; -
-
namespace
FacadeSample - {
-
class CipherMachine -
{ -
public string Encrypt( stringplainText) -
{ -
Console.Write("数据加密,将明文转换为密文:"); -
string es "";= -
char[] chars = plainText.ToCharArray(); -
foreach(char ch inchars) -
{ -
string c = (ch % 7).ToString(); -
es += c; -
} -
Console.WriteLine(es); -
return es; -
} -
} - }
-
//FileWriter.cs
-
using
System; -
using
System.IO; -
using
System.Text; -
-
namespace
FacadeSample - {
-
class FileWriter -
{ -
public void Write( stringencryptStr, stringfileNameDes) -
{ -
Console.WriteLine("保存密文,写入文件。"); -
FileStream fs = null; -
try -
{ -
fs = new FileStream(fileNameDes, FileMode.Create); -
byte[] str = Encoding.Default.GetBytes(encryptStr); -
fs.Write(str,0,str.Length); -
fs.Flush(); -
fs.Close(); -
} -
catch(FileNotFoundException e) -
{ -
Console.WriteLine("文件不存在!"); -
} -
catch(IOException e) -
{ -
Console.WriteLine(e.Message); -
Console.WriteLine("文件操作错误!"); -
} -
} -
} - }
-
//
EncryptFacade.cs -
namespace
FacadeSample - {
-
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( stringfileNameSrc, stringfileNameDes) -
{ -
string plainStr = reader.Read(fileNameSrc); -
string encryptStr = cipher.Encrypt(plainStr); -
writer.Write(encryptStr, fileNameDes); -
} -
} - }
-
//Program.cs
-
using
System; -
-
namespace
FacadeSample - {
-
class Program -
{ -
static void Main( string[]args) -
{ -
EncryptFacade ef = new EncryptFacade(); -
ef.FileEncrypt("src.txt", "des.txt"); -
Console.Read(); -
} -
} - }
读取文件,获取明文:Hello world! 数据加密,将明文转换为密文:233364062325 保存密文,写入文件。 |