• Dear Guest, Please do NOT forget to join our JAVA JOBS (ONLY) FACEBOOK GROUP to be aware of latest JAVA openings, and you may also post any JAVA related queries/jobs.

What is Adapter Pattern ?

#1
Adapter Pattern Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. It also known as Wrapper.

Use the Adapter pattern when :

1) You want to use an existing class, and its interface does not match the one you need

2) You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces

Code:
public class SquarePeg {
public void insert(String str) {
System.out.println("SquarePeg insert(): " + str);
}
}
Code:
/**
* The PegAdapter class.
* This is the Adapter class.
* It adapts a RoundPeg to a SquarePeg.
* Its interface is that of a SquarePeg.
*/
public class PegAdapter extends SquarePeg {
private RoundPeg roundPeg;
public PegAdapter(RoundPeg peg) {this.roundPeg = peg;}
public void insert(String str) {roundPeg.insertIntoHole(str);}
}
Code:
// Test program for Pegs.
public class TestPegs {
public static void main(String args[]) {
// Create some pegs.
RoundPeg roundPeg = new RoundPeg();
SquarePeg squarePeg = new SquarePeg();
// Do an insert using the square peg.
squarePeg.insert("Inserting square peg...");
// Now we'd like to do an insert using the round peg.
// But this client only understands the insert()
// method of pegs, not a insertIntoHole() method.
// The solution: create an adapter that adapts
// a square peg to a round peg!
PegAdapter adapter = new PegAdapter(roundPeg);
adapter.insert("Inserting round peg...");
}
}
 
Top