Adapter模式C++实现:
#include <iostream>
#include <cstring>
using namespace std;
typedef char String[30];
struct Point
{
int x;
int y;
};
class Car
{
private:
String name;
double speed;
public:
double getSpeed()
{
return speed;
}
void setSpeed(double sp)
{
speed=sp;
}
char *getName()
{
return name;
}
void setName(String Name)
{
strcpy(name,Name);
}
virtual void toString()
{
cout<<"Car Name:"<<name<<","<<"Speed:"<<speed<<endl;
}
};
class GPS
{
public:
virtual Point getLocation()=0;
};
class GPSCar:public Car,GPS
{
public:
Point getLocation()
{
Point point;
point.x=getSpeed();
point.y=getSpeed();
return point;
}
void toString()
{
Car::toString();
cout<<"坐标:("<<getLocation().x<<","<<getLocation().y<<")"<<endl;
}
};
int main()
{
Car car;
car.setName("Audi");
car.setSpeed(60);
car.toString();
cout<<endl;
GPSCar gpsCar;
gpsCar.setName("Audi");
gpsCar.setSpeed(60);
gpsCar.toString();
return 0;
}