简介
适配器模式:转接头
1、将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
2、保留现有类所提供的服务,向客户提供接口,以满足客户的期望。
适配器的优点:
1、将目标类和适配者类解耦
2、增加了类的透明性和复用性,将具体的实现封装在适配者类中,对于客户端类来说是透明的,而且提高了适配者的复用性
3、灵活性和扩展性都非常好,符合开闭原则
三种类型:
1、类适配
2、对象适配
3、缺省适配
放代码:
#include <iostream>
#include <string>
#ifdef ADA_CLASS
//220V电压
class high_voltage
{
public:
void add_high(void)
{
std::cout << "add 220v ." << std::endl;
}
};
//我们需要得低电压10V
class low_voltage
{
public:
virtual void add_low(void) = 0;
};
class convertor : public low_voltage, public high_voltage
{
public:
void add_low(void)
{
add_high();
change();
}
void change(void)
{
std::cout << "220v change 10v ." << std::endl;
}
};
#endif
#ifdef ADA_OBJ
//220V电压
class high_voltage
{
public:
high_voltage(int vol) : m_vol(vol)
{
}
void add_high(void)
{
std::cout << "add " << m_vol << "v ." << std::endl;
}
int m_vol;
};
//我们需要得低电压10V
class low_voltage
{
public:
virtual void add_low(void) = 0;
};
class convertor : public low_voltage
{
public:
convertor(high_voltage &hv) : m_hv(hv)
{
}
void add_low(void)
{
m_hv.add_high();
change();
}
void change(void)
{
std::cout << m_hv.m_vol << "v change 10v ." << std::endl;
}
high_voltage m_hv;
};
#endif
int main()
{
std::cout << "start-up .." << std::endl;
#ifdef ADA_CLASS
low_voltage *out = new convertor;
out->add_low();
delete out;
#endif
#ifdef ADA_OBJ
high_voltage v220(220);
high_voltage v110(110);
low_voltage *out = new convertor(v220);
out->add_low();
delete out;
out = new convertor(v110);
out->add_low();
delete out;
#endif
std::cout << "done .." << std::endl;
return 0;
}
运行结果: