Design Patterns

Here are two examples of the Adapter Pattern implemented in C#:

Example 1: Adapter for Legacy System Integration
Scenario

You have a legacy system that provides data in XML format, but your new system expects JSON format.


using System;

namespace AdapterPatternExample
{
    // Target Interface
    public interface ITarget
    {
        string GetRequest();
    }

    // Adaptee
    public class LegacySystem
    {
        public string GetXmlData()
        {
            return "John Doe";
        }
    }

    // Adapter
    public class Adapter : ITarget
    {
        private readonly LegacySystem _legacySystem;

        public Adapter(LegacySystem legacySystem)
        {
            _legacySystem = legacySystem;
        }

        public string GetRequest()
        {
            // Translate XML data to JSON format
            string xmlData = _legacySystem.GetXmlData();
            string jsonData = $"{{\"name\": \"John Doe\"}}"; // Simplified for example
            return jsonData;
        }
    }

    // Client
    class Program
    {
        static void Main(string[] args)
        {
            LegacySystem legacySystem = new LegacySystem();
            ITarget adapter = new Adapter(legacySystem);
            Console.WriteLine(adapter.GetRequest());
        }
    }
}