Work & Programming/System Design

[Structural Pattern] - Adapter

자전거통학 2024. 5. 15. 10:20

https://refactoring.guru/design-patterns/adapter

 

Adapter

/ Design Patterns / Structural Patterns Adapter Also known as: Wrapper Intent Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate. Problem Imagine that you’re creating a stock market monitoring app. The

refactoring.guru

 

서로 다른 두개의 객체의 interface를 보완하여 사용하게 해 줌. 

예시

 - XMLData : XMLTOJsonAdapter : JsonAdapter

 - Legacy version of Printer : PrinterVersionAdapter : Printer

 

 

예제 코드 

더보기
public class LegacyJson
{
    public void AddData(string key)
    {
    }
    public int GetData(int key) { return 0;}
}

// Responsible.
public class JsonAdaptor
{
    LegacyJson _legacyJson;

    public JsonAdaptor(LegacyJson target)
    {
        _legacyJson = target;
    }
    public void AddData(string key, int temp)
    {
        // key & data transform.
        _legacyJson.AddData(key);
    }
    public int GetData(string key)
    {
        int id;
        if(int.TryParse(key, out id))
            return _legacyJson.GetData(id);
        return 0;
    }
}

public class AdapterDemo
{
    public void Run()
    {
        LegacyJson oldJson = new LegacyJson();
        JsonAdaptor jsonAdaptor = new JsonAdaptor(oldJson);
        jsonAdaptor.AddData("key", 10);
        Console.WriteLine( jsonAdaptor.GetData("key") );
    }
}