程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 設計模式之外觀模式

設計模式之外觀模式

編輯:C++入門知識


外觀模式主要是用於對底層細節的封裝,當然,要結合每個系統的上層應用。
比如很多三維軟件就是對DX或者OpenGL的底層細節進行了封裝,可以這麼說吧

下面是類圖


下面是代碼
[cpp] 
// 外觀模式(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; 
 } 
  
  
 輸出結果: www.2cto.com
 //Connect to oracle now! 
 //Get data from Oracle now! 
 //Sucessful Decrypt! 
 //Sucessful Uncompress! 
 //Txt is put in this path: 
 //D:\temp.txt 
 //請按任意鍵繼續. . . 


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved