Adapter Pattern tutorial with real world example

Adapter Pattern is a structural Design Pattern. An Adapter converts the interface of a class into another interface clients expect. An Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

When To Use Adapter Design Pattern:

  • We can not change the library interface(code), since we may not have its source code. Even if we did have the source code, we probably should not change the library for each domain-specific application.
  • Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application.
  • Want to create a reusable class that cooperates with unrelated classes with incompatible interfaces.

Real Life Example of Adapter Pattern:
suppose I am a Programming Teacher, and I have two types of students in my class, the American students and the Brazilians students, since my Brazilians students don’t understand English, i have to have a transla-tor that will translate my lectures to my Brazilian students.

In this example, a Student class will be the Target, the translator will be the Adapter, and the Brazilians stu-dents will be the Adaptee, like the class diagram below:

Below is the example code:


import java.util.ArrayList;
import java.util.List;

// The Teacher Class
public class Teacher {

    List<Student> listStudent;

    public Teacher() {
	listStudent = new ArrayList<Student>();
    }

    public void teachStudents() {
	for (Student student : listStudent) {
	    student.learnLessonInEnglish();
	}
    }
}
// The Student Class
public abstract class Student {

    public abstract void learnLessonInEnglish();
}
// The Translator Class
public class Translator extends Student {

    BrazilianStudent brazilianStudent;

    public Translator(BrazilianStudent brazilianStudent) {
	super();
	this.brazilianStudent = brazilianStudent;
    }

    @Override
    public void learnLessonInEnglish() {
	// TODO Auto-generated method stub
	System.out.println("Translate to portuguese");
	brazilianStudent.learnLessonInPortuguese();
    }
}
// The AmericanStudent Class
public class AmericanStudent extends Student {

    @Override
    public void learnLessonInEnglish() {
	// TODO Auto-generated method stub
	System.out.println("Learning in english");
    }
}
// The BrazilianStudent Class
public class BrazilianStudent {
    public void learnLessonInPortuguese() {
	System.out.println("Learn in portuguese");
    }
}