设计模式-适配器模式(Adapter Pattern)

来源:互联网 发布:win7隐藏网络连接不上 编辑:程序博客网 时间:2024/04/30 19:41

应用场景:

1 系统需要使用现有的类,而这些类的接口不符合系统的接口。

2 想要建立一个可以重用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。

3 两个类所做的事情相同或相似,但是具有不同接口的时候。

4 旧的系统开发的类已经实现了一些功能,但是客户端却只能以另外接口的形式访问,但我们不希望手动更改原有类的时候。

5 使用第三方组件,组件接口定义和自己定义的不同,不希望修改自己的接口,但是要使用第三方组件接口的功能。

 

优点:

1 通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的。这样做更简单、更直接、更紧凑。

2 复用了现存的类,解决了现存类和复用环境要求不一致的问题。

3 将目标类和适配者类解耦,通过引入一个适配器类重用现有的适配者类,而无需修改原有代码。

4 一个对象适配器可以把多个不同的适配者类适配到同一个目标,也就是说,同一个适配器可以把适配者类和它的子类都适配到目标接口。

 

缺点:

 对于对象适配器来说,更换适配器的实现过程比较复杂。

简单实现:

#include <iostream>

using namespace std;

class Target

{

public:

virtual void Request()

{

cout<<"普通的请求"<<endl;

}

class Adaptee

{

public:

void SpecificalRequest()

{

cout<<"特殊请求"<<endl;

}

class Adapter :public Target

{

private:

Adaptee* ada;

public:

virtual void Request()

{

Ada->SpecificalRequest();

Target::Request();

}

Adapter()

{

ada=new Adaptee();

}

~Adapter()

{

delete ada;

}

};

客户端:

int main()

{

Adapter * ada=new Adapter();

Ada->Request();

delete ada;

return 0;

}

例二

#include <iostream>

#include <string>

using namespace std;

class Player

{

protected:

string name;

public:

Player(string strName) { name = strName; }

virtual void Attack()=0;

virtual void Defense()=0;

class Forwards : public Player

{

public:

Forwards(string strName):Player(strName){}

public:

virtual void Attack()

{

cout<<name<<"前锋进攻"<<endl;

}

virtual void Defense()

{

cout<<name<<"前锋防守"<<endl;

}

class Center : public Player

{

public:

Center(string strName):Player(strName){}

public:

virtual void Attack()

{

cout<<name<<"中场进攻"<<endl;

}

virtual void Defense()

{

cout<<name<<"中场防守"<<endl;

}

//为中场翻译

class TransLater: public Player

{

private:

Center *player;

public:

TransLater(string strName):Player(strName)

{

player = new Center(strName);

}

virtual void Attack()

{

Player->Attack();

}

virtual void Defense()

{

Player->Defense();

}

};

客户端

int main()

{

Player *p=new TransLater("小李");

p->Attack();

return 0;

}


0 0
原创粉丝点击