Design patterns: Adapter

The Adapter design pattern, which is also known as Wrapper design pattern, is used to convert the interface of an existing class into an interface expected by the client. In such a case the existing class has an incompatible interface. The adapter implements the compatible interface and executes its functionality by using the existing class. This could be necessary in case you use existing components which cannot or should not be changed but which should be integrated in your application.

For example you implement several data serializes which have the following interface. The data is represented as string in this example. The connection settings are use case specific and can be a file name, a database connection string or similar.

public interface IDataSerializer
{
    string ConnectionSettings { get; set; }
    string Read();
    void Write(string data);
}

In an existing library you already have a component which allows file access. It offers the following interface.

public interface IFileAccess
{
    void Open(string fileName);
    void Create(string fileName);
    void Close();
    string Read();
    void Write(string data);
}

You cannot change this existing class but you want to use it within your application. So you can implement an adapter which reuses the existing component but offers the expected interface.

public class FileSerializer : IDataSerializer
{
    private IFileAccess _fileAccess = new FileAccess();

    public string ConnectionSettings { get; set; }

    public string Read()
    {
        string data;

        _fileAccess.Open(ConnectionSettings);
        data = _fileAccess.Read();
        _fileAccess.Close();

        return data;
    }

    public void Write(string data)
    {
        _fileAccess.Create(ConnectionSettings);
        _fileAccess.Write(data);
        _fileAccess.Close();
    }
}
Advertisements
Dieser Beitrag wurde unter .NET, C#, Design Pattern, Softwaredesign veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s