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 boolean canDance(IDanceFilter iDanceFilter){
return iDanceFilter.canDance();
}
}
-----------------------------------------------------
This is a class that does not implemnt the IDanceFilter
interface.
-----------------------------------------------------
class Person{
public int graceLevel;
public Person(int grace){
this.graceLevel = grace;
}
}
-----------------------------------------------------
Here is the interface.
-----------------------------------------------------
public interface IDanceFilter{
public boolean canDance();
}
-----------------------------------------------------
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 implements IDanceFilter{
private Person person;
public PersonAdapter(Person person){
this.person = person;
}
public boolean canDance(){
if(person.graceLevel > 13)
return true;
else
return false;
}
}
-----------------------------------------------------
Test stub to show it all work.
-----------------------------------------------------
class Test{
public static void main(String[] args){
System.out.println("class: Test, method: main");
Vector generalPopulace = new Vector();
int count =0;
DanceJudges danceJudges = new DanceJudges();
for(int i =0; i<20; i++){
generalPopulace.add(new Person(i));
}
for(int i=0;i<generalPopulace.size();i++){
IDanceFilter iDanceFilter = new PersonAdapter((Person)generalPopulace.elementAt(i));
if(danceJudges.canDance(iDanceFilter))
count++;
}
System.out.println(count + " people can dance");
}
}
-----------------------------------------------------
Here is a tar with the above java classes in it.
adapter.tar