Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1816958
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2012-06-11 09:45:32

目标:双方都不适合修改的时候,可考虑适配器模式。

示例代码一:
#include
#include

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
#include

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("Messi Lee");
    p->Attack();
   
    return 0;
}
阅读(700) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~