设计模式

Adapter模式

2017-11-22  本文已影响0人  老练子丶2017

分为类模式和对象两种

类模式public继承接口,private继承实现

Adapter.h

#ifndef _ADAPTER_H

#define _ADAPTER_H

#include <iostream>

using namespace std;

class Target

{

public:

Target() {}

virtual ~Target() {}

virtual void Request() {

cout << "Target:Request" << endl;

}

};

class Adaptee

{

public:

Adaptee() {}

~Adaptee() {}

void SpecificRequest() {

cout << "Adaptee:SpecificRequest" << endl;

}

};

class Adapter : public Target,private Adaptee

{

public:

Adapter() {}

~Adapter() {}

void Request() {

SpecificRequest();

}

};

#endif // _ADAPTER_H

Adapter.cpp

#include "Adapter.h"

int main()

{

Adapter adapter;

adapter.Request();

return 0;

}

编译:make Adapter

对象模式使用委托(组合)来实现,这种写法应该见过挺多了

Adapter.h

#ifndef _ADAPTER_H

#define _ADAPTER_H

#include <iostream>

using namespace std;

class Target

{

public:

Target() {}

virtual ~Target() {}

virtual void Request() {

cout << "Target:Request" << endl;

}

};

class Adaptee

{

public:

Adaptee() {}

~Adaptee() {}

void SpecificRequest() {

cout << "Adaptee:SpecificRequest" << endl;

}

};

class Adapter : public Target

{

public:

Adapter(Adaptee* ade) {

_ade = ade;

}

~Adapter() {}

void Request() {

_ade->SpecificRequest();

}

private:

Adaptee* _ade;

};

#endif // _ADAPTER_H

Adapter.cpp:

#include "Adapter.h"

int main()

{

Adaptee* ade = new Adaptee;

Target* adt = new Adapter(ade);

adt->Request();

return 0;

}

编译:make Adapter

上一篇 下一篇

猜你喜欢

热点阅读