标签:
// Design Pattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <vector> using namespace std; //国产电器,工作在220V class ChineseAppliances { public: virtual void WorkOn220V() { cout << "220V正常工作" << endl; } }; //外国电器,工作在110V class ForeignAppliances { public: virtual void WorkOn110V() { cout << "110V正常工作" << endl; } }; //国产电器使用接口,我们就理解成插座吧 class ChineseSocket { private: vector<ChineseAppliances*> m_Socket; public: //接入电器 void AddAppliances(ChineseAppliances* app) { m_Socket.push_back(app); } //开启工作 void Work() { for (vector<ChineseAppliances*>::iterator it = m_Socket.begin(); it != m_Socket.end(); ++it) { (*it)->WorkOn220V(); } } }; int _tmain(int argc, _TCHAR* argv[]) { //国产电器容器(就理解成插座吧) ChineseSocket* chineseSocket = new ChineseSocket(); ChineseAppliances* chineseTV = new ChineseAppliances(); ForeignAppliances* foreignTV = new ForeignAppliances(); //我们有一个国产的插座,可以直接使用国内的电器 chineseSocket->AddAppliances(chineseTV); chineseSocket->Work(); //然而如果没有电源适配器的话,我们就不能在插座上使用国外电器了 //换句话说,我们即使可以使用,也不能按照国内的标准来使用,必须额外调用 //foreignTV->WorkOn110V(); system("pause"); return 0; }结果:
// Design Pattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <vector> using namespace std; //国产电器,工作在220V class ChineseAppliances { public: virtual void WorkOn220V() { cout << "220V正常工作" << endl; } }; //外国电器,工作在110V class ForeignAppliances { public: virtual void WorkOn110V() { cout << "110V正常工作" << endl; } }; //国产电器使用接口,我们就理解成插座吧 class ChineseSocket { private: vector<ChineseAppliances*> m_Socket; public: //接入电器 void AddAppliances(ChineseAppliances* app) { m_Socket.push_back(app); } //开启工作 void Work() { for (vector<ChineseAppliances*>::iterator it = m_Socket.begin(); it != m_Socket.end(); ++it) { (*it)->WorkOn220V(); } } }; //电源适配器 class Adapter : public ChineseAppliances { private: //对象适配器,保存一个需要被适配的对象实例 ForeignAppliances* m_foreignAppliances; public: Adapter(ForeignAppliances* app) :m_foreignAppliances(app) { cout << "我是适配器!" << endl; } virtual void WorkOn220V() override { cout << "通过适配器"; m_foreignAppliances->WorkOn110V(); } }; int _tmain(int argc, _TCHAR* argv[]) { //国产电器容器(就理解成插座吧) ChineseSocket* chineseSocket = new ChineseSocket(); ChineseAppliances* chineseTV = new ChineseAppliances(); ForeignAppliances* foreignTV = new ForeignAppliances(); Adapter* adapter = new Adapter(foreignTV); //我们有一个国产的插座,可以直接使用国内的电器 chineseSocket->AddAppliances(chineseTV); //有了适配器,我们的外国电器就可以被当做国产电器,插座同志对他们就一视同仁啦 chineseSocket->AddAppliances(adapter); chineseSocket->Work(); system("pause"); return 0; }结果:
标签:
原文地址:http://blog.csdn.net/puppet_master/article/details/51326210