Wednesday, 11 July 2018

Adapter Design Pattern - Structural

 Allows two incompatible interfaces to work together.

Sample Code Download: AdapterDesignPattern.zip (Visual Studio 2017 Console App)


Add Employee and EmployeeManager classes

[Serializable]
public class Employee
{
    Employee() { }
    public Employee(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
    [XmlAttribute]
    public int Id { get; set; }
    [XmlAttribute]
    public string Name { get; set; }
}

public class EmployeeManager
{
    public List Employees;
    public EmployeeManager()
    {
        Employees = new List
        {
            new Employee(1, "John"),
            new Employee(2, "Michael"),
            new Employee(3, "Jason")
        };
    }

    public virtual string GetAllEmployees()
    {
        var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

        var serializer = new XmlSerializer(Employees.GetType());

        var settings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = true
        };

        using (var stream = new StringWriter())
        {
            using (var writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, Employees, emptyNamepsaces);
                return stream.ToString();
            }
        }

    }
}


Add IEmployee Interface

public interface IEmployee
{
    string GetAllEmployees();
}

Add Employee Adapter class implement IEmployee and inherit EmployeeManager Class.

public class EmployeeAdapter : EmployeeManager, IEmployee
{
    public override string GetAllEmployees()
    {
        var returnXml = base.GetAllEmployees();
        var doc = new XmlDocument();
        doc.LoadXml(returnXml);
        return JsonConvert.SerializeObject(doc, Newtonsoft.Json.Formatting.Indented);
    }
}

Invoke the EmployeeAdapter class in the main program which is our client. Run the application and notice that the xmlString is converted to JsonString with The Adapter Implementation.

class Program
{
    static void Main(string[] args)
    {
        IEmployee emp = new EmployeeAdapter();
        var value = emp.GetAllEmployees();
        Console.WriteLine(value);
        Console.ReadLine();
    }
}




Structural Design Patterns   Adapter | Bridge | Composite | Decorator | Facade | Flyweight | Proxy