The Adapter pattern is a structural design pattern that allows two incompatible interfaces to work together. It involves creating a wrapper or adapter class that can translate the methods and properties of one interface to another, allowing objects that use one interface to work with objects that use a different interface.
Here’s an example of how the Adapter pattern can be used in C#:
// Adaptee interface
public interface ITarget
{
void Request();
}
// Adaptee implementation
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Adaptee: SpecificRequest");
}
}
// Adapter implementation
public class Adapter : ITarget
{
private Adaptee _adaptee;
public Adapter(Adaptee adaptee)
{
_adaptee = adaptee;
}
public void Request()
{
Console.WriteLine("Adapter: Request");
_adaptee.SpecificRequest();
}
}
// Client code
static void Main(string[] args)
{
Adaptee adaptee = new Adaptee();
ITarget target = new Adapter(adaptee);
target.Request();
}
In this example, the ITarget
interface defines the target interface that the client code expects to use. The Adaptee
class represents an interface that is incompatible with ITarget
. The Adapter
class is the bridge between the two interfaces. It wraps an instance of Adaptee
and exposes a method that matches the ITarget
interface, while internally calling the appropriate method of Adaptee
.
When the client code calls the Request
method on the target
object, it is actually calling the Request
method of the Adapter
object. The Adapter
object, in turn, calls the SpecificRequest
method of the wrapped Adaptee
object, effectively translating the call from the ITarget
interface to the Adaptee
interface.