Adapter Pattern in C#


Adapter Pattern

Download code from here

Introduction

GOF describes adapter as a pattern: “Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

Motivation

We need to change our old system to new one.

When using third party API, we might need the wrapper which contains the functionality of the third party API. Yes, we can use the API directly on the client side but there may be the cases where the client doesn’t understand the object of third party API. In this scenario, we need the wrapper class which wrap-up the third party API to the class that client can understand. In real time scenario we might need the extra additional plug to connect to the electricity. That additional plug is an ‘Adaptor’.

Design

There are two ways we can implement Adapter, one using class and other using object. I will focus onto the later method in this article. Let’s see the class structure of both ways.

Adapter using class

Adapter using object

Adapter contains the instance of adaptee which needs to be change in type to Target.

Code

Full code can be downloaded from here.

I am using very simple example to demonstrate Adapter pattern using object.  Consider the ThirdPartyAPI class which is our adaptee and we needs to write wrapper for this so that we can use client familiar object i.e. FormualCalculator


/// <summary>

/// Adaptee class which needs to be converted into FormulaCalculator

/// </summary>

class ThirdPartyAPI

{

public void CalculateFormula()

{

Console.WriteLine("Third party tool formula calculation");

}

}

Adapter class


/// <summary>

/// Target class

/// </summary>

class FormulaCalculator

{

public virtual void CalculateFormula()

{

Console.WriteLine("CalculateFormula formula FormulaCalculator");

}

}

FormulaCalculatorAdaptor is used as wrapper for this purpose


/// <summary>

/// Adapter class

/// </summary>

class FormulaCalculatorAdapter : FormulaCalculator

{

private ThirdPartyAPI _api;

public FormulaCalculatorAdapter()

{

_api = new ThirdPartyAPI();

}

public override void CalculateFormula()

{

_api.CalculateFormula();

}

}

Conclusion

Adapter pattern is very useful when we need to write wrapper class on third party API.  Next consider the scenario that you have two different classes and you are using functionalities of both those classes in your client. The code would be cleaner and easy to understand if those both classes use same interface and we can use single interface in client. Adapter can play vital role in this scenario by providing common interface.

MVC Pattern


MVC Pattern

Code can be downloaded from here

Introduction

MVC pattern is software design pattern. It separates the dependency between the actual business object and view so that different views and different business objects can interact independently. If you are not familiar with the term view you can consider it as the user interface (UI).  Avoiding the unnecessary coupling is really useful but difficult task in software architecture. MVC beautifully isolates the application logic from the UI introducing loose coupling and adding independent testing functionalities.

Motivation

  • Consider you like to display the certain set of data but in different UI. What should you do? If…else is of course not the good solution. Moreover, program should always tend to separate UI and Business Logic (BL). Let’s assume you manage to display the data in two different UI as user request. But two is not the end. What if your client wants to add certain other type of UI display? Now you will stuck if there is coupling between application data and user interface data. More there is the new UI requirement more complex will be your system.
  • Assume a web page.  A person can be good web page designer but it doesn’t mean he can understand complex business object.  But a programmer can understand the complex business object and he/she doesn’t need to understand about web rendering. Separation is necessary here so that two can work independently.

Architecture

Model

Model represents the core functionalities like data representation and processing. It processes the data behind the scene. In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

View

It manages the display information. It renders the information from model into a form, suitable for user interaction.

Controller

It is the middle class between model and view. It contains both model and view and manage their interaction. It accepts input and passes the responsibilities to model and view as required.

Code

I want to give a very simple example of MVC model. You can find complete code here. There will be three different interfaces for model, view and controller and there will be two views which implements IView, two model which implements IModel and a controller which implements IModel. Consider the model interface IModel.


public interface IModel

{

List<Information> Informations { get; }

int HelloCount { get; }

void AddHello();

void RemoveHello();

void AddObserver(IView view);

void RemoveObserver(IView view);

void NotifyObservers();

}

In above interface Informations contains the data to display in view. I have used the Observer pattern to notify the views from model.

My view interface


public interface IView

{

void Show();

void SetUp(IModel model);

void Display(IModel model);

void ChangeRemoveState(bool state);

void ChangeAddState(bool state);

void AddHello();

}

It contains the SetUp function which sets the all three component and creates observer. The    most important function here is Display which accepts the IModel. It displays the information of model in UI. Note that there is interface in parameter so that it can accepts any class which implements IModel.

And my controller Interface.


interface IController

{

void SetModel(IModel model);

void SetView(IView view);

void RequestAddHello();

void RequestRemoveHello();

}

Consider one View, ListForm which implements the IView interface and display the information in ListView. It will not know what type of model. Its job is to just display the information of model. There are certain other functionalities which I added to show the program flow. For easy, I am not writing the designer code. Please, download code for complete solution.


public partial class ListForm : Form, IView

{

private IController _controller;

private IModel _model;

public ListForm()

{

InitializeComponent();

}

public void Display(IModel model)

{

listViewInformation.Items.Clear();

foreach (Information info in model.Informations)

listViewInformation.Items.Add(new ListViewItem(new string[] { info.Name, info.Address }));

}

public void AddHello()

{

_controller.RequestAddHello();

}

public void SetUp(IModel model)

{

if (_model != null)

_model.RemoveObserver(this);

_model = model;

_controller = new InformationControl(_model, this);

_model.AddObserver(this);

Display(_model);

}

public void Show()

{

ShowDialog();

Display(_model);

}

private void buttonAddHello_Click(object sender, EventArgs e)

{

_controller.RequestAddHello();

}

private void buttonRemoveHello_Click(object sender, EventArgs e)

{

_controller.RequestRemoveHello();

}

public void ChangeRemoveState(bool state)

{

buttonRemoveHello.Enabled = state;

}

public void ChangeAddState(bool state)

{

buttonAddHello.Enabled = state;

}

}

Whenever there is AddHello and RemoveHello call, it calls the controller to handle the request because we need to change the model accordingly.

I am writing code of a Model here. Please note that I have used abstract Model class which implements IModel. Whenever there are certain changes in Model it notifies the observer (view).


class FirstNameFirstModel : Model

{

public override List<Information> Informations

{

get

{

if (_informations == null)

{

_informations = new List<Information>(0);

foreach (XmlNode node in RootNode.ChildNodes)

{

Information info = new Information

{

Name = node.SelectSingleNode("//FirstName").InnerText + ", " + node.SelectSingleNode("//LastName").InnerText,

Address = node.SelectSingleNode("//Address").InnerText

};

_informations.Add(info);

}

}

return _informations;

}

}

public override void RemoveHello()

{

_helloCount--;

if (_helloCount < 0)

return;

Update();

}

public override void AddHello()

{

_helloCount++;

if (_helloCount > 10)

return;

Update();

}

private void Update()

{

string hello = string.Empty;

for (int i = 0; i < _helloCount; i++)

hello += "Hello ";

_informations = new List<Information>(0);

foreach (XmlNode node in RootNode.ChildNodes)

{

Information info = new Information

{

Name = hello + node.SelectSingleNode("//FirstName").InnerText + ", " + node.SelectSingleNode("//LastName").InnerText,

Address = node.SelectSingleNode("//Address").InnerText

};

_informations.Add(info);

}

NotifyObservers();

}

}

InformationControl class is used to behave as concreted controller.


class InformationControl : IController

{

private IModel _model;

private IView _view;

public InformationControl(IModel model, IView view)

{

_model = model;

_view = view;

}

public void SetModel(IModel model)

{

_model = model;

}

public void SetView(IView view)

{

_view = view;

}

public void RequestAddHello()

{

_model.AddHello();

UpdateState();

}

private void UpdateState()

{

_view.ChangeAddState(_model.HelloCount <= 10);

_view.ChangeRemoveState(_model.HelloCount > 0);

}

public void RequestRemoveHello()

{

_model.RemoveHello();

UpdateState();

}

}

Whenever there is update it calls UpdateState which decides the View’s UI status.

Conclusion

MVC model separates the application logic from UI so that two can vary independently and code becomes clean. Software design should be ‘Open for extension and close for extension’. MVC model greatly supports this principle by supporting any view and any model without actually changing the logic.

Next is What?

In my next article I will try to give you the overview of MVP model.