Java
Usage examples: The Adapter pattern is pretty common in Java code. It’s very often used in systems based on some legacy code. In such cases, Adapters make legacy code work with modern classes.
There are some standard Adapters in Java core libraries:
java.io.InputStreamReader(InputStream)(returns aReaderobject)java.io.OutputStreamWriter(OutputStream)(returns aWriterobject)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()and#unmarshal()
Identification: Adapter is recognizable by a constructor which takes an instance of a different abstract/interface type. When the adapter receives a call to any of its methods, it translates parameters to the appropriate format and then directs the call to one or several methods of the wrapped object.
Fitting square pegs into round holes
This simple example shows how an Adapter can make incompatible objects work together.
round
round/RoundHole.java: Round holes
package refactoring_guru.adapter.example.round;
/**
* RoundHoles are compatible with RoundPegs.
*/
public class RoundHole {
private double radius;
public RoundHole(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public boolean fits(RoundPeg peg) {
boolean result;
result = (this.getRadius() >= peg.getRadius());
return result;
}
}round/RoundPeg.java: Round pegs
square
square/SquarePeg.java: Square pegs
adapters
adapters/SquarePegAdapter.java: Adapter of square pegs to round holes
Demo.java: Client code
OutputDemo.txt: Execution result
Last updated