adapter 模式

把一个类的接口转换为另一个类的接口(该接口是客户端期待的接口)。Adapter让类共同工作,而不会因为接口的不兼容性而不能用。
#include <iostream>

using namespace std;
class Hindu
{
public:
    virtual ~Hindu() = default;
    virtual void performsHinduRitual() const = 0;
};

class HinduFemale:public Hindu
{
public:
    virtual void performsHinduRitual()const override
    {
    cout<<"Hindu girl performs Hindu ritual"<<endl;
    }
};

class Muslim
{
public:
    virtual ~Muslim() = default;
    virtual void performsMusliRitual() const = 0;
};

class MuslimFemale:public Muslim
{
public:
    virtual void performsMusliRitual()const override
    {
        std::cout<<"Muslim Girl performs Muslim ritual."<<endl;
        }
};

class HinduRitual
{
public:
    void carryOutRitual(Hindu *hindu)
    {
        cout<<"On with the Hindu rituals!"<<endl;
        hindu->performsHinduRitual();
    }

};

class HinduAdapter:public Hindu
{
private:
    Muslim* muslim;
public:
    HinduAdapter(Muslim* m):muslim(m){}
    virtual void performsHinduRitual() const override {muslim->performsMusliRitual();
    }
};

int main()
{
   HinduFemale* hinduGirl = new HinduFemale;
	MuslimFemale* muslimGirl = new MuslimFemale;
	HinduRitual hinduRitual;
//	hinduRitual.carryOutRitual (muslimGirl);  // Will not compile of course since the parameter must be of type Hindu*.
	HinduAdapter* adaptedMuslim = new HinduAdapter (muslimGirl);  // muslimGirl has adapted to become a Hindu!

	hinduRitual.carryOutRitual (hinduGirl);
	hinduRitual.carryOutRitual (adaptedMuslim);  // So now muslimGirl, in the form of adaptedMuslim, participates in the hinduRitual!
                // Note that muslimGirl is carrying out her own type of ritual in hinduRitual though.

	delete adaptedMuslim;  // adaptedMuslim is not needed anymore
	delete muslimGirl; // muslimGirl is not needed anymore
    delete hinduGirl; // hinduGirl is not needed anymore, too
	return 0;
}

在该段代码中,主要包括如下几种类。


通过HinduAdapter实现从MuslimFemale转为HinduFemale。

rituali表示仪式的意思

Hidu表示印度教

Muslim表示穆斯林

class HinduAdapter:public Hindu
{
private:
    Muslim* muslim;
public:
    HinduAdapter(Muslim* m):muslim(m){}
    virtual void performsHinduRitual() const override {muslim->performsMusliRitual();
    }
};

通过adpter的类,当传入参数为muslim时,则执行muslim的函数。

HinduRitual调用的时候,可以根据不同的类,执行相同的接口,实现不同的调用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值