Day 9 – Adapter Pattern

어댑터 패턴은 호환되지 않는 인터페이스를 가진 개체가 함께 작동할 수 있도록 하는 구조적 디자인 패턴입니다. 이는 호환되지 않는 두 인터페이스 사이의 브리지 역할을 합니다. 이 패턴은 기존 클래스를 사용하려고 하지만 해당 인터페이스가 필요한 클래스와 일치하지 않을 때 특히 유용합니다.

어댑터 패턴은 새로운 시스템을 기존 시스템과 통합하거나 기존 코드를 변경하지 않고 라이브러리 및 프레임워크를 사용할 때 자주 사용됩니다. 이는 시스템 유연성을 향상시키고 코드 재사용성을 촉진합니다.


Codes

프로그램의 Adaptee Class는 ITarget 인터페이스를 통해 작동하기를 바라지만 Adaptee 클래스에는 다른 인터페이스가 있습니다. Adapter 클래스는 ITarget 인터페이스를 구현하고 Adaptee 개체를 래핑하여 Adaptee의 메서드를 ITarget 인터페이스로 변환합니다. 따라서 클라이언트는 Adapter를 통해 Adaptee의 기능을 사용할 수 있습니다.

Adaptee.cs
// 'Adaptee' class has an incompatible interface.
public class Adaptee
{
    public string GetSpecificRequest()
    {
        return "Specific request.";
    }
}
C#
ITarget.cs
// 'ITarget' interface is the interface clients expect to work with.
public interface ITarget
{
    string GetRequest();
}
C#
Adapter.cs
// 'Adapter' class implements the 'ITarget' interface and wraps an 'Adaptee' object.
public class Adapter : ITarget
{
    private readonly Adaptee _adaptee;

    public Adapter(Adaptee adaptee)
    {
        _adaptee = adaptee;
    }

    public string GetRequest()
    {
        return $"This is the adapted '{_adaptee.GetSpecificRequest()}'";
    }
}
C#
Program.cs
Adaptee adaptee = new Adaptee();
ITarget target = new Adapter(adaptee);

Console.WriteLine("Adaptee interface is incompatible.");
Console.WriteLine("But with adapter client can call it's method.");
Console.WriteLine(target.GetRequest());
C#

Links

Comments

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다