C++ Adapter
The adapter pattern "adapts" one class to another.
To see the value imagine that you only have access to
binaries for DanceJudges and Person classes.
This is a class that uses the IDanceFilter interface.
-----------------------------------------------------
class DanceJudges{
public:
bool canDance(IDanceFilter* iDanceFilter);
};
bool DanceJudges::canDance(IDanceFilter* iDanceFilter){
return iDanceFilter->canDance();
}
-----------------------------------------------------
This is a class that does not implemnt the IDanceFilter
interface.
-----------------------------------------------------
class Person{
public:
Person(int grace);
int graceLevel;
};
Person::Person(int grace){
Person::graceLevel = grace;
}
-----------------------------------------------------
Here is the interface.
-----------------------------------------------------
class IDanceFilter{
public:
virtual ~IDanceFilter(){};
virtual bool canDance() = 0;
};
-----------------------------------------------------
This is the adapter class. This class will enable the
DanceJudges class to use the Person class as if it had
implemented the IDanceFilter interface.
-----------------------------------------------------
class PersonAdapter : public IDanceFilter{
public:
PersonAdapter(Person* person);
bool canDance();
private:
Person* person;
};
PersonAdapter::PersonAdapter(Person* person){
PersonAdapter::person = person;
}
bool PersonAdapter::canDance(){
if(PersonAdapter::person != 0
&& PersonAdapter::person->graceLevel > 13){
return true;}
else
return false;
}
-----------------------------------------------------
Test stub to show it all work.
-----------------------------------------------------
int main(){
std::cout<<"main: START\n";
DanceJudges danceJudges;
Person* person = new Person(14);
IDanceFilter* iDanceFilter = new PersonAdapter(person);
if(danceJudges.canDance(iDanceFilter))
std::cout<<"they can dance\n";
else
std::cout<<"they can NOT dance\n";
std::cout<<"main: END\n";
//QUESTION
delete person;
delete iDanceFilter;
return 0;
}
-----------------------------------------------------
Here is a tar with the above java classes in it.
C++_adapter.tar