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(); } }