Adapter pattern

De Banane Atomic
Aller à la navigationAller à la recherche

Definition

Convert the interface of a class into another interface that clients expect.
The Adapter pattern lets classes work together that could not otherwise because of incompatible interfaces.

  • Match otherwise incompatible interfaces

Exemple

Rectangle.cs
public interface IRectangle
{
    int GetArea();
}

public class Rectangle : IRectangle
{
    private readonly int width;
    private readonly int lenght;

    public Rectangle(int width, int lenght)
    {
        this.lenght = lenght;
        this.width = width;
    }

    public int GetArea() => width * lenght;
}
Disk
public interface IDisk
{
    double ComputeArea();
}

public class Disk : IDisk
{
    private readonly int radius;

    public Disk(int radius)
    {
        this.radius = radius;
    }

    public double ComputeArea() => 2 * Math.PI * radius;
}
DiskToRectangleAdapter.cs
public class DiskToRectangleAdapter : IRectangle
{
    private readonly IDisk disk;

    public DiskToRectangleAdapter(IDisk disk)
    {
        this.disk = disk;
    }

    public int GetArea() => (int)disk.ComputeArea();
}
Csharp.svg
var rectangles = new List<IRectangle>();
IRectangle rectangle = new Rectangle(40, 30);
rectangles.Add(rectangle);

IDisk disk = new Disk(100);
IRectangle adaptedDisk = new DiskToRectangleAdapter(disk);
rectangles.Add(adaptedDisk);

DisplayArea(rectangles);

void DisplayArea(IEnumerable<IRectangle> rectangles)
{
    foreach (var rectangle in rectangles)
    {
        Console.WriteLine(rectangle.GetArea());
    }
}