A:adapter模式中的类模式:
问题:类A中的方法要用到类B提供的接口.
实现方法:
新生成一个类C,公共继承于类A,私有继承于类B:
这样.类C,拥有了类A中的公有方法,也拥有了类B中提供的公有接口.
然后,C重载类A的方法,调用B提供的接口 .
这里有一个关于接口继承和实现继承的问题:
接口继承:就是继承父类的接口还可以向外部提供接口.
实现继承:就是继承父类的接口以后就不可以向外部提供了..
代码:
class A
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
A();
virtual ~A();
vitual void operation(); //供C重载
};
class B
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
B();
virtual ~B();
void operationB();
};
class C:public A,private B
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
C();
~C():
void operation()
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedSubBlock.gif)
{
this->operationB();
}
}
B:Adapter 的对象模式
这种模式则和bridge模式中有些类似,采用类组合的方式.对于类A,和类B;
新创建一个类C,公共继承于类A,然后在类C中创建一个类B的对象指针.这样就可以通过这个指针来调用类B提供的接口 .
class C:public A
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
C();
~C();
void operation
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
pB->operationB();
}
private:
B *pB;
};