Jump to content

Adapter pattern

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 80.242.205.162 (talk) at 15:33, 3 August 2013 (Added a comment that the alternative naming of the pattern is identical to the Decorator's alternative naming according to the GOF book.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, the adapter pattern (often referred to as the wrapper pattern or simply a wrapper - an alternative naming shared with the Decorator Pattern according to the GoF Design Patterns book ) is a design pattern that translates one interface for a class into a compatible interface.[1] 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 (i.e. flags) but the client requires individual boolean values, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).

Definition

An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

Structure

There are two types of adapter patterns:[1]

Object 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 polymorphic interfaces to achieve its goal. The adapter is created by implementing or inheriting 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.[1]

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 that 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 {
    private ClassA classA = null;

    public ClassAFormat1(final ClassA A) {
        classA = A;
    }

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

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

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

(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 that can be retrofitted to an existing object hierarchy.


Implementation of Adapter pattern

When implementing the adapter pattern, for clarity use the class name [AdapteeClassName]To[Interface]Adapter, for example DAOToProviderAdapter. It should have a constructor method with adaptee class variable as parameter. This parameter will be passed to the instance member of [AdapteeClassName]To[Interface]Adapter.

public class AdapteeToClientAdapter implements Client {

    private final Adaptee instance;

    public AdapteeToClientAdapter(final Adaptee instance) {
         this.instance = instance;
    }

    @Override
    public void clientMethod() {
       // call Adaptee's method(s) to implement Client's clientMethod
    }

}

C# Implementation of Adapter Pattern

Please find below the C# implementation[2] of the Adapter Pattern. In this example, we create a collection of IEmployee objects. Since employee inherits from IEmployee it can naturally be added to the list. However, the Consultant class is unrelated to IEmployee. In order to allow this class to be added to the same list, we create an Adapter class: EmployeeAdapter which wraps the Consultant class with the IEmployee interface, allowing it to be added to the same list.

using System.Collections.Generic;    

class Program
{
    static void Main(string[] args)
    {
        List<IEmployee> list = new List<IEmployee>();
        list.Add(new Employee("Tom"));
        list.Add(new Employee("Jerry"));
        list.Add(new ConsultantToEmployeeAdapter("Bruno"));  //consultant from existing class
        ShowHappiness(list);
    }

    //*** Code below from the existing library does not need to be changed ***
    static void ShowHappiness(List<IEmployee> list)
    {
        foreach (IEmployee i in list)
            i.ShowHappiness();
    }
}

//from the existing library, does not need to be changed
public interface IEmployee
{
    void ShowHappiness();
}

public class Employee : IEmployee
{
    private string name;
    
    public Employee(string name)
    {
        this.name = name;
    }

    void IEmployee.ShowHappiness()
    {
        Console.WriteLine("Employee " + this.name + " showed happiness");
    }
}

//existing class does not need to be changed
public class Consultant
{
    private string name;

    public Consultant(string name)
    {
        this.name = name;
    }

    protected void ShowSmile()
    {
        Console.WriteLine("Consultant " + this.name + " showed smile");
    }
}

public class ConsultantToEmployeeAdapter: Consultant, IEmployee
{
    public ConsultantToEmployeeAdapter(string name) : base(name)
    {
    }

    void IEmployee.ShowHappiness()
    {
        base.ShowSmile();  //call the parent Consultant class
    }
}

See also

  • Delegation, strongly relevant to the object adapter pattern.
  • Dependency inversion principle, which 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).
  • Wrapper function

References

  1. ^ a b c Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bates, Bert (2004). "Head First Design Patterns" (paperback). O'Reilly Media: 244. ISBN 978-0-596-00712-6. OCLC 809772256. Retrieved April 30, 2013. {{cite journal}}: Cite journal requires |journal= (help)
  2. ^ Thank you to devshed for providing the original version of this code under open license