1. 适配器模式
#include <iostream>
using namespace std;
class ThreePhasePlug {
public:
void doThreePhasePlug() {
cout << "three phase" << endl;
}
};
class TwoPhaseOutlet {
public:
virtual void doPlug() = 0;
virtual ~TwoPhaseOutlet() {};
};
//类的适配
class OutletConverter : public TwoPhaseOutlet, public ThreePhasePlug {
public:
void doPlug() {
doConvert();
doThreePhasePlug();
}
private:
void doConvert() {
cout << "Do convert" << endl;
}
};
//对象的适配
class OutletObjConverter : public TwoPhaseOutlet {
public:
OutletObjConverter(ThreePhasePlug* plug) : m_plug(plug) {};
virtual void doPlug() {
doConvert();
m_plug->doThreePhasePlug();
}
private:
void doConvert() {
cout << "Do convert" << endl;
}
private:
ThreePhasePlug* m_plug = nullptr;
};
int main(void) {
/*OutletConverter* outer = new OutletConverter();
outer->doPlug();*/
auto* outer = new OutletObjConverter(new ThreePhasePlug());
outer->doPlug();
delete outer;
return 0;
}
2. 门面模式
原理
门面模式也叫做外观模式,实质就是一个封装接口,通常是将一类功能或者一个层次功能用一个函数封装起来,供客户端统一调用。
应用场景
- 当你要为一个复杂子系统提供一个简单接口时;
- 客户程序与抽象类的实现部分之间存在着很大依赖性;
- 当你需要构建一个层次的子系统时,使用Facade模式定义子系统中每层的入口点;
UML类图
代码实现:
FacadePattern.cpp
#include <iostream>
using namespace std;
#define DELETE(pointer) delete pointer; pointer=nullptr
class Television {
public:
void openSwitch() { cout << "open switch of Television!" << endl; }
void closeSwitch() { cout << "close switch of Television!" << endl; }
};
class WaterHeater {
public:
void openSwitch() { cout << "open switch of WaterHeater!" << endl; }
void closeSwitch() { cout << "close switch of WaterHeater!" << endl; }
};
class FacadePattern { //门面模式
public:
void openSwitch() { television.openSwitch(); waterHeater.openSwitch(); } //提供客户端使用的统一接口
void closeSwitch() { television.closeSwitch(); waterHeater.closeSwitch(); }
private:
Television television; //子系统类,只跟门面模式类耦合,不跟客户端偶尔;实现子系统与客户端的接口隔离
WaterHeater waterHeater;
};
void doFacadePattern()
{
FacadePattern *facadePattern = new FacadePattern();
facadePattern->openSwitch();
facadePattern->closeSwitch();
DELETE(facadePattern);
}
main.cpp
#include <iostream>
extern void doFacadePattern();
int main()
{
doFacadePattern();
system("pause");
return 1;
}
参考:
标签:cout,适配器,模式,门面,设计模式,pointer,void From: https://www.cnblogs.com/xcodingfork/p/17153786.html