Thursday, 2 March 2023

Adapter Pattern with example

The Adapter Pattern is used to convert the interface of one class into another interface that is expected by the client. This is useful when you have two incompatible interfaces that need to work together.

Here's an example implementation of the Adapter pattern in C#:

public interface ITarget
{
    void Request();
}

public class Adaptee
{
    public void SpecificRequest()
    {
        Console.WriteLine("Specific request.");
    }
}

public class Adapter : ITarget
{
    private readonly Adaptee adaptee;

    public Adapter(Adaptee adaptee)
    {
        this.adaptee = adaptee;
    }

    public void Request()
    {
        adaptee.SpecificRequest();
    }
}

In this implementation, we have an interface ITarget that defines the Request method, an Adaptee class that has a SpecificRequest method, and an Adapter class that implements the ITarget interface and adapts the Adaptee class to work with the ITarget interface.

The Adapter class takes an instance of the Adaptee class in its constructor, and implements the Request method by calling the SpecificRequest method of the Adaptee class.

To use the adapter, you can simply create an instance of the Adapter class with an instance of the Adaptee class, like this:


Adaptee adaptee = new Adaptee();
ITarget target = new Adapter(adaptee);

target.Request(); // Output: Specific request.


In this example, we create an instance of the Adaptee class, and use it to create an instance of the Adapter class by passing it to the Adapter constructor. We then call the Request method on the ITarget instance, which in turn calls the SpecificRequest method of the Adaptee instance.

This example demonstrates how the Adapter pattern can be used to adapt an incompatible interface to a compatible one, allowing the two interfaces to work together seamlessly.

0 comments:

Post a Comment

Please do not enter any spam link in the message box.