C++设计模式-适配器模式
生活随笔
收集整理的這篇文章主要介紹了
C++设计模式-适配器模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
?
基本概念
代碼與實例
?
基本概念
適配器(Adapter)模式:將一個類的接口轉換為客戶希望的另一個接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。
?
當系統的數據和行為都正常,但接口不負荷時,可以考慮使用適配器,目的是使控制范圍之外的一個原有對象與某個接口匹配。適配器模式主要應用于希望復用一些現存的類,但是接口又與復用的環境要求不一致的情況。
?
什么時候使用適配器模式:
? ? ? ? ? 1. 使用一個已經存在的類,但如果它的接口,也就是它的方法和你的要求不同時使用。
? ? ? ? ? 2. 客戶代碼要求統一調用同一接口。
? ? ? ? ? 3. 雙方都不太容易修改的時候再使用適配器模式;
?
本人在此總結下,這個就像套子一樣,比如在某個結構里面,有了很多設計模式和功能,但我這個系統,又可以作為另外一個大系統的小功能,而那個大系統又有某種規范,此時給自己的系統帶一個套子,使得他能順利的進入那個大系統,按F進入坦克。哈哈哈!
?
代碼與實例
結構如下所示(此圖來源于大話設計模式):
程序運行截圖如下:
源碼如下:
Head.h
#ifndef HEAD_H #define HEAD_H//客戶期待的接口,目標可以是具體的或者抽象的類,也可以是接口 class Target{public:virtual void request();virtual ~Target(); };//需要適配的類 class Adaptee{public:void specificRequest(); };//通過內部包裝一個Adaptee對象,把源接口轉換為目標接口 class Adapter : public Target{public:void request();~Adapter();Adapter();private:Adaptee *adaptee; };#endif HEAD_HHead.cpp
#include "Head.h" #include <iostream> #include <string> using namespace std;void Target::request() {cout << "普通請求!" << endl; } Target::~Target() {cout << "Target::~Target() called!" << endl; }void Adaptee::specificRequest() {cout << "特殊請求!" << endl; }void Adapter::request() {adaptee->specificRequest(); }Adapter::~Adapter() {cout << "Adapter::~Adapter() called!" << endl; }Adapter::Adapter() {//建立一個私有的Adaptee對象adaptee = new Adaptee; }Main.cpp
#include "Head.h" #include <iostream> #include <string> using namespace std;int main(int *argc, int *argv[]){Target *target = new Adapter;target->request();delete target;getchar();return 0; }?
總結
以上是生活随笔為你收集整理的C++设计模式-适配器模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-QWebView官方解
- 下一篇: C++设计模式-桥接模式