Jump to content

Adapter pattern: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
JMatthews (talk | contribs)
Undid revision 361246101 Revert spurious use of final; correct for-each loop.
Line 169: Line 169:


class LegacyLine {
class LegacyLine {
public void draw(final int x1, final int y1, final int x2, final int y2) {
public void draw(int x1, int y1, int x2, int y2) {
System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','
System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','
+ y2 + ')');
+ y2 + ')');
}
}
}
}

class LegacyRectangle {
class LegacyRectangle {
public void draw(final int x, final int y, final int w, final int h) {
public void draw(int x, int y, int w, int h) {
System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
+ " and height " + h);
+ " and height " + h);
}
}
}
}

public class AdapterDemo {
public class AdapterDemo {
public static void main(final String[] args) {
public static void main(String[] args) {
final Object[] shapes = { new LegacyLine(), new LegacyRectangle() };
Object[] shapes = {
new LegacyLine(), new LegacyRectangle()
};

// A begin and end point from a graphical editor
// A begin and end point from a graphical editor
final int x1 = 10, y1 = 20;
int x1 = 10, y1 = 20;
final int x2 = 30, y2 = 60;
int x2 = 30, y2 = 60;

for (final Object obj : shapes) {
for (Object obj : shapes) {
if (LegacyLine.class.isInstance(obj)) {
if (LegacyLine.class.isInstance(obj)) {
LegacyLine.class.cast(obj).draw(x1, y1, x2, y2);
LegacyLine.class.cast(obj).draw(x1, y1, x2, y2);

} else if (LegacyRectangle.class.isInstance(obj)) {
} else if (LegacyRectangle.class.isInstance(obj)) {
LegacyRectangle.class.cast(obj).draw(Math.min(x1, x2),
LegacyRectangle.class.cast(obj).draw(Math.min(x1, x2), Math.min(y1, y2),
Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
Math.abs(x2 - x1), Math.abs(y2 - y1));
}
}
}
}
Line 210: Line 210:
//a user-friendly common interface to legacy-specific peculiar interfaces.
//a user-friendly common interface to legacy-specific peculiar interfaces.


class LegacyLine {
class LegacyLine
{
public void draw(final int x1, final int y1, final int x2, final int y2) {
public void draw(int x1, int y1, int x2, int y2)
{
System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','
+ y2 + ')');
System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','
+ y2 + ')');
}
}
}
}


class LegacyRectangle {
class LegacyRectangle
{
public void draw(final int x, final int y, final int w, final int h) {
public void draw(int x, int y, int w, int h)
{
System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
+ " and height " + h);
+ " and height " + h);
}
}
}
}


interface Shape {
interface Shape
{
void draw(int x1, int y1, int x2, int y2);
void draw(int x1, int y1, int x2, int y2);
}
}


class Line implements Shape {
class Line implements Shape
{
private final LegacyLine adaptee = new LegacyLine();
private LegacyLine adaptee = new LegacyLine();
public void draw(int x1, int y1, int x2, int y2)

{
public void draw(final int x1, final int y1, final int x2, final int y2) {
adaptee.draw(x1, y1, x2, y2);
adaptee.draw(x1, y1, x2, y2);
}
}
}
}


class Rectangle implements Shape {
class Rectangle implements Shape
{
private final LegacyRectangle adaptee = new LegacyRectangle();
private LegacyRectangle adaptee = new LegacyRectangle();
public void draw(int x1, int y1, int x2, int y2)

{
public void draw(final int x1, final int y1, final int x2, final int y2) {
adaptee.draw(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),
adaptee.draw(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),
Math.abs(y2 - y1));
Math.abs(y2 - y1));
}
}
}
}


public class AdapterDemo {
public class AdapterDemo
{
public static void main(final String[] args) {
public static void main(String[] args)
{
final Shape[] shapes = { new Line(), new Rectangle() };
Shape[] shapes =

{
new Line(), new Rectangle()
};
// A begin and end point from a graphical editor
// A begin and end point from a graphical editor
final int x1 = 10, y1 = 20;
int x1 = 10, y1 = 20;
final int x2 = 30, y2 = 60;
int x2 = 30, y2 = 60;
for (Shape shape : shapes)

for (final Shape shape : shapes) {
shape.draw(x1, y1, x2, y2);
shape.draw(x1, y1, x2, y2);
}
}
}
}
}

Revision as of 15:02, 10 May 2010

In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value.

Structure

There are two types of adapter pattern:

Adapter pattern

In this type of adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object.

The object adapter pattern expressed in UML. The adapter hides the adaptee's interface from the client.
The object adapter pattern expressed in LePUS3.

Class Adapter pattern

This type of adapter uses multiple inheritance to achieve its goal. The adapter is created inheriting from both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure interface class, especially in languages such as Java that do not support multiple inheritance.

The class adapter pattern expressed in UML.
The class adapter pattern expressed in LePUS3

The adapter pattern is useful in situations where an already existing class provides some or all of the services you need but does not use the interface you need. A good real life example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed. A link to a tutorial that uses the adapter design pattern is listed in the links below.

A further form of runtime Adapter pattern

There is a further form of runtime Adapter pattern as follows:

It is desired for classA to supply classB with some data, let us suppose some String data. A compile time solution is:

classB.setStringData(classA.getStringData());

However, suppose that the format of the string data must be varied. A compile time solution is to use inheritance:

Format1ClassA extends ClassA {
 public String getStringData() {
  return format(toString());
 }
}

and perhaps create the correctly "formatting" object at runtime by means of the Factory pattern.

A solution using "adapters" proceeds as follows:

(i) define an intermediary "Provider" interface, and write an implementation of that Provider interface which wraps the source of the data, ClassA in this example, and outputs the data formatted as appropriate:

public interface StringProvider {
    public String getStringData();
}

public class ClassAFormat1 implements StringProvider {
    ClassA classA;

    public ClassAFormat1(ClassA classA) {
        this.classA = classA;
    }

    public String getStringData() {
        return format(classA.toString());
    }
}


(ii) Write an Adapter class which returns the specific implementation of the Provider:

public class ClassAFormat1Adapter extends Adapter {
 public Object adapt(Object o) {
  return new ClassAFormat1((ClassA) o);
 }

 public boolean isAdapterFor(Class c) {

  return c.equals(StringProvider.class);
 }

}


(iii) Register the Adapter with a global registry, so that the Adapter can be looked up at runtime:

AdapterFactory.getInstance().registerAdapter(ClassA.class, ClassAFormat1Adapter.class, "format1");

(iv) In your code, when you wish to transfer data from ClassA to ClassB, write:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format1");

StringProvider provider = (StringProvider) adapter.adapt(classA);

String string = provider.getStringData();

classB.setStringData(string);


or more concisely:

classB.setStringData((StringProvider) AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format1").adapt(classA)).getStringData();

(v) The advantage can be seen in that, if it is desired to transfer the data in a second format, then look up the different adapter/provider:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format2");

(vi) And if it is desired to output the data from ClassA as, say, image data in Class C:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, ImageProvider.class, "format1");

ImageProvider provider = (ImageProvider) adapter.adapt(classA);

classC.setImage(provider.getImage());

(vii) In this way, the use of adapters and providers allows multiple "views" by ClassB and ClassC into ClassA without having to alter the class hierarchy. In general, it permits a mechanism for arbitrary data flows between objects which can be retrofitted to an existing object hierarchy.

Example - Object Adapter

Ruby

class Adaptee
  def specific_request
    # do something
  end
end

class Adapter
  def initialize(adaptee)
    @adaptee = adaptee
  end

  def request
    @adaptee.specific_request
  end
end

client = Adapter.new(Adaptee.new)
client.request

Python

class Adaptee:
    def __init__(self):
        pass
    
    def specific_request(self):
        return 'Adaptee'
 
class Adapter:
    def __init__(self, adaptee):
        self.adaptee = adaptee
 
    def request(self):
        return self.adaptee.specific_request()
 
client = Adapter(Adaptee())
print client.request()

Java

//Before
//Because the interface between Line and Rectangle objects is 
//incompatible, the user has to recover the type of each shape and manually supply the correct arguments. 

class LegacyLine {
    public void draw(int x1, int y1, int x2, int y2) {
        System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ',' 
          + y2 + ')');
    }
}
 
class LegacyRectangle {
    public void draw(int x, int y, int w, int h) {
        System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
          + " and height " + h);
    }
}
 
public class AdapterDemo {
    public static void main(String[] args) {
        Object[] shapes = {
            new LegacyLine(), new LegacyRectangle()
        };
        // A begin and end point from a graphical editor
        int x1 = 10, y1 = 20;
        int x2 = 30, y2 = 60;
        
        for (Object obj : shapes) {
            if (LegacyLine.class.isInstance(obj)) {
                LegacyLine.class.cast(obj).draw(x1, y1, x2, y2);
            } else if (LegacyRectangle.class.isInstance(obj)) {
                LegacyRectangle.class.cast(obj).draw(Math.min(x1, x2), Math.min(y1, y2),
                  Math.abs(x2 - x1), Math.abs(y2 - y1));
            }
        }
    }
}
//line from (10,20) to (30,60)
//rectangle at (10,20) with width 20 and height 40



//After
//The Adapter’s “extra level of indirection” takes care of mapping
//a user-friendly common interface to legacy-specific peculiar interfaces. 

class LegacyLine
{
    public void draw(int x1, int y1, int x2, int y2)
    {
        System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ',' 
          + y2 + ')');
    }
}

class LegacyRectangle
{
    public void draw(int x, int y, int w, int h)
    {
        System.out.println("rectangle at (" + x + ',' + y + ") with width " + w
          + " and height " + h);
    }
}

interface Shape
{
  void draw(int x1, int y1, int x2, int y2);
}

class Line implements Shape
{
    private LegacyLine adaptee = new LegacyLine();
    public void draw(int x1, int y1, int x2, int y2)
    {
        adaptee.draw(x1, y1, x2, y2);
    }
}

class Rectangle implements Shape
{
    private LegacyRectangle adaptee = new LegacyRectangle();
    public void draw(int x1, int y1, int x2, int y2)
    {
        adaptee.draw(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),
          Math.abs(y2 - y1));
    }
}

public class AdapterDemo
{
    public static void main(String[] args)
    {
        Shape[] shapes = 
        {
            new Line(), new Rectangle()
        };
        // A begin and end point from a graphical editor
        int x1 = 10, y1 = 20;
        int x2 = 30, y2 = 60;
        for (Shape shape : shapes)
          shape.draw(x1, y1, x2, y2);
    }
}
//line from (10,20) to (30,60)
//rectangle at (10,20) with width 20 and height 40

Example - Class Adapter

Python

class Adaptee1:
    def __init__(self, *args, **kw):
        pass
    
    def specific_request(self):
        return 'Adaptee1'

class Adaptee2:
    def __init__(self, *args, **kw):
        pass
    
    def specific_request(self):
        return 'Adaptee2'
 
class Adapter(Adaptee1, Adaptee2):
    def __init__(self, *args, **kw):
        Adaptee1.__init__(self, *args, **kw)
        Adaptee2.__init__(self, *args, **kw)
 
    def request(self):
        return Adaptee1.specific_request(self), Adaptee2.specific_request(self)
 
client = Adapter()
print client.request()

See also

Wrapper function

Dependency inversion principle can be thought of as applying the Adapter pattern, when the high-level class defines their own (adapter) interface to the low-level module (implemented by an Adaptee class)