DEV Community

Abdullah Al Mahmud
Abdullah Al Mahmud

Posted on • Edited on

🔎Exploring Design Patterns: Adapter Pattern

General Structure:

Target (IJsonAdapter): The interface that clients expect to use

Adaptee (LegacyXmlSystem): The existing class that needs to be adapted

Adapter (XmlToJsonAdapter): The class that bridges between Target and Adaptee

Client: The code that works with the Target interface

public interface IJsonAdapter
{
    string GetJsonData();
}

// Adaptee: Legacy system that needs to be adapted
public class LegacyXmlSystem
{
    public string GetXmlData()
    {
        return "<data> some XML data </data>";
    }
}

// Adapter: Adapter implementation
public class  XmlToJsonAdapter : IJsonAdapter
{
    private LegacyXmlSystem _xmlSystem;

    public XmlToJsonAdapter(LegacyXmlSystem xmlSystem)
    {
        _xmlSystem = xmlSystem;
    }

    public string GetJsonData()
    {
        string xmlData = _xmlSystem.GetXmlData();
        // converting xml to json
        return "{ data: some XML data converted to JSON }";
    }
}
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • Integrating legacy code with new systems
  • Making incompatible interfaces work together
  • Reusing existing classes with incompatible interfaces
  • Converting data formats between systems
  • Maintaining backward compatibility

Benefits:

  • Promotes reusability of existing code
  • Provides clean separation of concerns
  • Makes incompatible code work together without modifying source
  • Follows Single Responsibility Principle
  • Enhances maintainability

Limitations:

  • Can add complexity to the codebase
  • May require creating multiple adapters for different interfaces
  • Could impact performance due to additional layer
  • Might make debugging more challenging
  • Not suitable when extensive interface modifications are needed

The real-world example in the code shows adapting XML data to JSON format. The pattern is particularly useful in scenarios like:

  • Database interface adaptations
  • Third-party library integration
  • API versioning
  • File format conversions
  • Payment gateway integrations

✨ You can find design pattern codes in this repository

✨ Exploring Design Patterns Other Posts

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

đź‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay