04 Dec 2023
The Adapter design pattern is a structural pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. In C#, the Adapter pattern typically involves the following main components:
-
Target Interface:
- The interface that the client code expects or depends on.
- The client code interacts with objects that conform to this interface.
public interface ITarget { void Request(); } -
Adaptee:
- The existing class that has a different interface than what the client code expects.
- It is the class that needs to be adapted to work with the client code.
public class Adaptee { public void SpecificRequest() { Console.WriteLine("Specific Request"); } } -
Adapter:
- Implements the Target interface.
- Wraps the Adaptee to make it compatible with the Target interface.
- Delegates calls from the Target interface methods to the corresponding methods of the Adaptee.
public class Adapter : ITarget { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void Request() { adaptee.SpecificRequest(); } } -
Client:
- The code that interacts with objects through the Target interface.
- The client is unaware of the actual implementation of the Adaptee.
class Client { static void Main() { // Create an instance of the Adaptee Adaptee adaptee = new Adaptee(); // Create an Adapter and pass the Adaptee to it ITarget adapter = new Adapter(adaptee); // Use the Target interface to make a request adapter.Request(); } }
In the example above, ITarget is the target interface that the client code expects. Adaptee is an existing class with a different interface. The Adapter class is responsible for adapting the Adaptee class to the ITarget interface. The Client interacts with the Adapter through the ITarget interface without being aware of the Adaptee class.
This pattern is particularly useful when integrating new components or libraries that have incompatible interfaces with the existing codebase. The Adapter acts as a bridge between the existing code and the new components, allowing them to work together seamlessly.