C++设计模式-适配器模式
目錄
?
?
基本概念
代碼與實例
?
基本概念
適配器(Adapter)模式:將一個類的接口轉(zhuǎn)換為客戶希望的另一個接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。
?
當(dāng)系統(tǒng)的數(shù)據(jù)和行為都正常,但接口不負(fù)荷時,可以考慮使用適配器,目的是使控制范圍之外的一個原有對象與某個接口匹配。適配器模式主要應(yīng)用于希望復(fù)用一些現(xiàn)存的類,但是接口又與復(fù)用的環(huán)境要求不一致的情況。
?
什么時候使用適配器模式:
? ? ? ? ? 1. 使用一個已經(jīng)存在的類,但如果它的接口,也就是它的方法和你的要求不同時使用。
? ? ? ? ? 2. 客戶代碼要求統(tǒng)一調(diào)用同一接口。
? ? ? ? ? 3. 雙方都不太容易修改的時候再使用適配器模式;
?
本人在此總結(jié)下,這個就像套子一樣,比如在某個結(jié)構(gòu)里面,有了很多設(shè)計模式和功能,但我這個系統(tǒng),又可以作為另外一個大系統(tǒng)的小功能,而那個大系統(tǒng)又有某種規(guī)范,此時給自己的系統(tǒng)帶一個套子,使得他能順利的進(jìn)入那個大系統(tǒng),按F進(jìn)入坦克。哈哈哈!
?
代碼與實例
結(jié)構(gòu)如下所示(此圖來源于大話設(shè)計模式):
程序運行截圖如下:
源碼如下:
Head.h
#ifndef HEAD_H #define HEAD_H//客戶期待的接口,目標(biāo)可以是具體的或者抽象的類,也可以是接口 class Target{public:virtual void request();virtual ~Target(); };//需要適配的類 class Adaptee{public:void specificRequest(); };//通過內(nèi)部包裝一個Adaptee對象,把源接口轉(zhuǎn)換為目標(biāo)接口 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; }?
總結(jié)
以上是生活随笔為你收集整理的C++设计模式-适配器模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-QWebView官方解
- 下一篇: SQL工作笔记-达梦数据库关于时间的函数