設計模式C++實現十三:適配器模式

來源:互聯網
上載者:User

標籤:c++   物件導向   設計模式   適配器模式   

適配器模式(Adapter):將一個類的介面轉換成客戶希望的另一個介面。使得原本介面不相容而不能在一個工作的那些類可以一起工作。

使用情境:當系統的資料和行為都正確,但介面不同時,我們可以考慮使用適配器模式來匹配介面。主要應用在希望複用一些存在的類,但是介面又和複用環境要去不同時使用。

#ifndef ADAPTER_H#define ADAPTTE_H#include<iostream>#include<string>using namespace std;class Player{protected:string name;public:virtual void Attack()=0;virtual void Defense() = 0;};class Forwards :public Player{public:Forwards(string n) {name = n; }void Attack(){cout << "前鋒 " << name << " 進攻。\n";}void Defense(){cout << "前鋒 " << name << " 防守。\n";}};class Guards :public Player{public:Guards(string n) { name = n; }void Attack(){cout << "後衛 " << name << " 進攻。\n";}void Defense(){cout << "後衛 " << name << " 防守。\n";}};class ForeignCenter :public Player{friend class Translator;//聲明Translator為友元類,專業它就可以訪問ForeignCenter裡面的資訊,即翻譯可以和外國球員交流public:ForeignCenter(){}ForeignCenter(string n) { name = n; }private://聲明為私人意味著外籍中鋒不能明白教練進攻和防守的意圖。void Attack(){cout << "中鋒 " << name << " 進攻。\n";}void Defense(){cout << "中鋒 " << name << " 防守。\n";}};class Translator :public Player{ForeignCenter Fcenter;public:Translator(string n){ Fcenter.name=n; }void Attack(){Fcenter.Attack();}void Defense(){Fcenter.Defense();}};#endif

#include"Adapter.h"int main(){Guards mc("麥迪");mc.Attack();mc.Defense();Forwards Bt("巴蒂爾");Bt.Defense();Bt.Attack();Translator Meimei("姚明");//聲明Meimei是姚明的翻譯,當Meimei響應進攻時,就是Meimei告訴姚明要進攻Meimei.Attack();Meimei.Defense();return 0;}



設計模式C++實現十三:適配器模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.