// 在美国使用电脑, 110V的接口
class ChargeInUSA
{
public:
ChargeInUSA() {cout<<"in usa we need use 120v voltage to charge the computer"<<endl;}
virtualvoid ChargeComInUSA()
{
cout<<"charge computer with american principle 120V"<<endl;
}
};
// 中国充电,220V的接口
class ChargeInChina
{
public:
voidChargeComInChina()
{
cout<<"charge computer with chinese principle 220v"<<endl;
}
};
// 类适配器
class VoltageAdapter : public ChargeInUSA, private ChargeInChina
{
public:
virtualvoidChargeComInUSA()
{
cout<<"using voltage adapter, change 120v to 220v ..."<<endl;
ChargeComInChina();
}
};
// 使用
class LiveInUSA
{
public:
LiveInUSA(){cout<<"live in america, we have different principle with china"<<endl;}
void SetChrgVol(ChargeInUSA* c){chrg = c;}
void ChargeCom(){chrg->ChargeComInUSA();}
private:
ChargeInUSA* chrg;
};
// 如上面的例子, 实际应用中,我们可能会在很多地方用到chrg->ChargeComInUSA(); 那么现在如要使用ChargeComInChina()接口, 显然不能到处取修改已经使用的接口, 那么这里使用适配器则是非常好的设计int main()
{
LiveInUSA* xiaoming = new LiveInUSA;
xiaoming->SetChrgVol(new VoltageAdapter);
xiaoming->ChargeCom();
return0;
}