(转载)Adapter Design Pattern in C++

An adapter pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

It comprises three components:

  • Target: This is the interface with which the client interacts.
  • Adaptee: This is the interface the client wants to interact with, but can’t interact without the help of the Adapter.
  • Adapter: This is derived from Target and contains the object of Adaptee.

When I shifted from India to London, I took along many of my electrical appliances with me. But there was one problem using them, the pin shape. In India, all the appliances have round pins whereas in London they are flat pinned. Now how do we overcome this problem as I was not ready to buy new plugs. So the adapter came to my rescue (and saved lots of pounds!!!)

I got hold of an adapter plug which has round pins as input and the other end with flat pins (India to UK adapters). This is how I used them with the adapter pattern.

Class description:

  • <AbstractPlug>: Abstract Target class
  • <Plug>: Concrete Target class
  • <AbstractSwitchBoard>: Abstract Adaptee class
  • <SwitchBoard>: Concrete Adaptee class
  • <Adapter>: Adapter class, our saviour

// Abstract Target
class AbstractPlug {
public:
  void virtual RoundPin(){}
  void virtual PinCount(){}
};
// Concrete Target
class Plug : public AbstractPlug {
public:
  void RoundPin() {
    cout << " I am Round Pin" << endl;
  }
  void PinCount() {
    cout << " I have two pins" << endl;
  }
};
// Abstract Adaptee
class AbstractSwitchBoard {
public:
  void virtual FlatPin() {}
  void virtual PinCount() {}
};
// Concrete Adaptee
class SwitchBoard : public AbstractSwitchBoard {
public:
  void FlatPin() {
        cout << " Flat Pin" << endl;
  }
  void PinCount() {
        cout << " I have three pins" << endl;
  }
};
// Adapter
class Adapter : public AbstractPlug {
public:
  AbstractSwitchBoard *T;
  Adapter(AbstractSwitchBoard *TT) {
        T = TT;
  }
  void RoundPin() {
        T->FlatPin();
  }
  void PinCount() {
        T->PinCount();
  }
};
// Client code
void _tmain(int argc, _TCHAR* argv[])
{
  SwitchBoard *mySwitchBoard = new SwitchBoard; // Adaptee
  // Target = Adapter(Adaptee)
  AbstractPlug *adapter = new Adapter(mySwitchBoard);
  adapter->RoundPin();
  adapter->PinCount();
}

 reference:  http://www.codeproject.com/Tips/595716/Adapter-Design-Pattern-in-Cplusplus

转载于:https://www.cnblogs.com/sparkles/p/3165331.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值