设计模式之外观模式

原文地址: http://blog.csdn.net/iuhsihsow


外观模式主要是用于对底层细节的封装,当然,要结合每个系统的上层应用。

比如很多三维软件就是对DX或者OpenGL的底层细节进行了封装,可以这么说吧大笑


下面是类图



下面是代码

// 外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式
 // 定义了一个高程接口,这个接口使得这一子系统更加容易使用。
 
 
 // 情景假设
 // 某一软件,运行时需要连接数据库,获取数据文本,假设为txt文本
 // 数据库是Oracle,从数据库中取出的是加密过的文件
 // 解密子系统是decryption,解密之后是一个rar,需要解压
 // 解压子系统是rar
 // 现在创建一个facade掩盖此过程,做到用户给一个输入,就能得到输出。
 
 
 // 这个例子比较简单,因为就是封装下接口,不需要用到多态之类的
 // 所以每个类就只声明一个对象即可
 
 // 最终用户知道的细节越少越好,迪米特法则
 
 #include "stdafx.h"
 #include <Windows.h>
 
 //数据库子系统
 class OracleDB
 {
 public:
 	bool GetDataFromDB(long id, byte* &pBuf)
 	{
 		printf("Connect to oracle now!\n");
 		printf("Get data from Oracle now!\n");
 		return true;
 	}
 protected:
 private:
 };
 
 //解密子系统
 class Decryption
 {
 public:
 	bool Decrypt(byte* &pBuf) 
 	{
 		byte *pDecryption = NULL;
 		pBuf = pDecryption;
 		printf("Sucessful Decrypt!\n");
 		return true;
 	}
 protected:
 private:
 };
 
 //解压缩子系统
 class RARSys
 {
 public:
 	bool UnCompress(byte* &pBuf, char* pPath)
 	{
 		byte* pUncompress = NULL;
 		pBuf = pUncompress;
 		printf("Sucessful Uncompress!\n");
 		if (WriteData(pPath))
 		{
 			return true;
 		}
 		
 	}
 protected:
 private:
 	bool WriteData(char* pPath)
 	{
 		printf("Txt is put in this path:\n");
 		printf(pPath);
 		printf("\n");
 		return true;
 	}
 };
 
 
 //外观类
 class Facade
 {
 public:
 	bool GetTxt(long id, char *pPath)
 	{
 		OracleDB	db;
 		Decryption	dp;
 		RARSys		rs;
 		byte *pBuf;
 		db.GetDataFromDB(id, pBuf);
 		dp.Decrypt(pBuf);
 		rs.UnCompress(pBuf, pPath);
 		return true;
 	}
 protected:
 private:
 };
 
 
 int _tmain(int argc, _TCHAR* argv[])
 {
 	Facade fd;
 	fd.GetTxt(100, "D:\\temp.txt");
 	return 0;
 }
 
 
 输出结果:
 //Connect to oracle now!
 //Get data from Oracle now!
 //Sucessful Decrypt!
 //Sucessful Uncompress!
 //Txt is put in this path:
 //D:\temp.txt
 //请按任意键继续. . .



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值