One of the important design patterns is the adapter design pattern, let's say you have new mobile and the old charger not compatible with the new mobile then you have two options to buy a new charger or buy an adapter that reuses the old charger, so we buy an adapter instead of buy a new charger because the charger is more expensive.
So this behavior what adapter design pattern use is to reuse existing code instead of adding new implementation.
Let's go in-depth and show examples.
I have an adaptee EmployeeManager class that get employees in XML like this,
- public class EmployeeManager {
- public List < Employee > employees;
- public EmployeeManager() {
- employees = new List < Employee > ();
- this.employees.Add(new Employee(1, "John"));
- this.employees.Add(new Employee(2, "Michael"));
- this.employees.Add(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();
- settings.Indent = true;
- settings.OmitXmlDeclaration = true;
- using(var stream = new StringWriter())
- using(var writer = XmlWriter.Create(stream, settings)) {
- serializer.Serialize(writer, employees, emptyNamepsaces);
- return stream.ToString();
- }
- }
- }
What task in order for me to get employees in JSON so instead of adding a new implementation we will reuse employeeManager.
We will add a target folder and add IEmployee interface like this,
- public interface IEmployee {
- string GetAllEmployees();
- }
Second, we will add an Adapter folder and add EmployeeAdapter class that implements EmployeeManager and IEmployee interface,
- public class EmployeeAdapter: EmployeeManager, IEmployee {
- public override string GetAllEmployees() {
- string returnXml = base.GetAllEmployees();
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(returnXml);
- return JsonConvert.SerializeObject(doc, Newtonsoft.Json.Formatting.Indented);
- }
- }
The last client will use EmployeeAdapter to get an employee in JSON,
- class Program {
- static void Main(string[] args) {
- IEmployee emp = new EmployeeAdapter();
- string value = emp.GetAllEmployees();
- Console.WriteLine(value);
- Console.ReadLine();
- }
- }