Design Pattern - Adapter
Thursday, January 15th, 2009In all my previous posts I wrote about Creational Design Patterns: Singleton, Abstract Factory, Factory method, Prototype and Builder. In this posts I will introduce you with: Adapter - Structural Pattern.
Definition of “Adapter” says:
Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces, so it converts the interface of a class into another interface clients expect. Here is UML diagram
Here is the Java code which demonstrates using of Adapter pattern. This is abstract class Shape. I use it to define some very simple interface.
abstract class Shape {
public abstract double GetVolume();
}
and now I create 2 clases which implements this interface
public class Square extends Shape {
private int radius;
public Square(int r)
{
radius = r;
}
public double GetVolume()
{
return radius * radius;
}
}
public class Triangle extends Shape {
private int a;
public Triangle(int x)
{
a = x;
}
public double GetVolume()
{
return (a * a * Math.sqrt(3)) /4;
}
}
and what if we have one more class but with the wrong interface (functionality is ok, but interface not)
public class XCircle {
private int radius;
public XCircle(int r)
{
radius = r;
}
public double XGetVolume()
{
return radius * radius * Math.PI;
}
}
but we need Cirlce class. Here is what we do than:
public class Circle extends Shape {
private int radius;
private XCircle circle;
public Circle(int r)
{
radius = r;
circle = new XCircle(radius);
}
public double GetVolume()
{
return circle.XGetVolume();
}
}
at the end here is simple client application to demonstrate how it works:
public class Circle extends Shape {
private int radius;
private XCircle circle;
public Circle(int r)
{
radius = r;
circle = new XCircle(radius);
}
public double GetVolume()
{
return circle.XGetVolume();
}
}
that is all ![]()





Recent Comments