Builder Pattern in C#


Builder Pattern

Full code can be downloaded from here.

Introduction

GOF definition –“Separate the construction of a complex object from its representation so that the same construction process can create different representations.” Builder pattern focuses on constructing a complex object step by step and returns the product as the final step. It creates one of the several targets.

Motivation

The most common motivation for using Builder is to simplify the client code which creates the complex object. The main advantage will be client can still make the object but without knowing what actually is happening inside. Consider an example of creating different vehicles like car, motorcycle and bus. What builder helps us to simplify here is giving the client the complete vehicle with the only information about what is the type.  Client does not need to worry how the different vehicles are being created.

Architecture

Builder contains the abstract interface for building the product. And there will be different ConcreteBuilder which has the different implantations of creating product. Director contains the instance of the Builder and constructs the product according to the Builder instance. Product is our final output which we need to create.

Code

I have created the sample program which demonstrates the way to develop the different rules similar to the Microsoft Outlook. Full code can be downloaded from here.

Builder abstract class

</span>

abstract class RuleBuilder

{

protected Rule _rule;

public Rule Rule { get { return _rule; } }


public abstract void SetDescription();


public abstract void BuildCondition();


public abstract void BuildAction();


}

Product class


class Rule

{

IDictionary<string, string> _properties;


public Rule(string name)

{

_properties = new Dictionary<string, string>(0);

_properties["name"] = name;

}


public string this[string key]

{

get { return _properties[key]; }

set { _properties[key] = value; }

}


public void Show()

{

Console.WriteLine("------Rule {0}------", _properties["name"]);

Console.WriteLine("Description: {0}", _properties["description"]);

Console.WriteLine("Condition: {0}", _properties["condition"]);

Console.WriteLine("Result: {0}", _properties["action"]);

}

}

Director class


class MailManager

{

public RuleBuilder RuleBuilder { set; private get; }


public void CreateRule()

{

RuleBuilder.SetDescription();

RuleBuilder.BuildAction();

RuleBuilder.BuildCondition();

}

}

Note the RuleBuilder instance in MailManager. We can omit it with parameter in CreateRule method. I did above code so as to follow the class diagram.

Output

——Rule Move Rule——

Description: Move the mail from one folder to another

Condition: When new mail arrived with title ‘xyz’

Result: Escape inbox and copy mail to ‘abc’ folder

——Rule Delete Rule——

Description: Delete the mail with specific condition

Condition: When new mail arrived with title ‘xxx’ OR mail arrived from address xxx@hotmail.com

Result: delete it

Conclusion

Builder is a type of Creational pattern like Factory but it gives us more control in each step of construction process. It is not a widely used pattern but it is an important one. Whenever we need to create different objects with some set of operations then we must think about Builder.

Advertisements

Bridge Design Pattern in C#


Bridge

Download full code from here.

Introduction

GOF definition: “Decouple an abstraction from its implementation so that the two can vary independently.” Bridge uses encaptulation, aggregation and use (probably) inheritence to separate responsibilities into different classes. This pattern is useful when both the abstraction as well as what it does often vary.

Motivation

Consider a situation that we have a different type of switch mechanism which has different implementation of ‘On’ and ‘Off’. For instance, Computer has different type of powering on/off mechanism than that of lamp. In this case we can use the implementation in a single class using if…else but what if we need to add those mechanism for water pump, mobile, vehicles. Then our code will be ugly if we continue to do the work using if…else. The Bridge design pattern proposes refactoring these issues by using two orthogonal hierarchies – one for independent abstractions, and the other for dependent implementations.

Architecture

This class structure shows that the Abstraction is completely separated from the implementation which can vary independently. Abstraction contains the instance of the implementor. In fact Abstraction behaves as wrapper of implementor but can have its own set of logic. Here I have shown only one refined abstraction but it can be many also according to the need of the logic.

Code

Complete code can be downloaded from here.

Here, I will give you the very simple example of the Bridge pattern which uses the one RefinedAbstraction and two different concrete implementations which defined the On/Off mechanism for Computer and Electric Lamp.

AbstractSwitch


abstract class AbstractSwitch

{

public AbstractSwitch(bool initialSwitchState)

{

_switchState = initialSwitchState;

}

public virtual bool On()

{

return _switchImplementation.On();

}

public virtual bool Off()

{

return _switchImplementation.Off();

}

public virtual void ShowInformation()

{

_switchImplementation.ShowInformation();

}

public SwitchImplementation SwitchImplementation

{

get { return _switchImplementation; }

set

{

_switchImplementation = value;

if (_switchState)

_switchImplementation.On();

}

}

private bool _switchState;

private SwitchImplementation _switchImplementation;

}

Notice the SwitchImplementation instance and it’s uses in methods in AbstactSwitch class.

Abstract Implementation


abstract class SwitchImplementation

{

public abstract bool On();

public abstract bool Off();

public abstract void ShowInformation();

}

Our every concrete implementation will extend the SwitchImplementation instance.

Conclusion

Unlike Adapter which makes things after designed Bridge makes things work before they are. Note that Bridge is designed up-front to let the abstraction and the implementation vary independently.

Observer Pattern in C#


Observer Pattern

Download code from here.

Introduction

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It is a subset of publish-subscribe pattern. We use observer as a view in MVC pattern. C# is very much suited for this language with the power of events and delegates.

Motivation

We always need loose coupling between objects. Observer pattern promotes loose coupling. Subject doesn’t depend on the observer but they are registered/unregistered to the subject.

Consider the football game in which all players (as well as linesman/referee) need to move and take position according to the position of the ball. There must present some sort of mechanism which send message to all observers about the position change activity of the ball. Yes, observer pattern is the useful one.

Architecture

Subject is the one which register/unregister the observer and notifies the observers about the state. Observers have reference of subject and get updated as subject changes. Note the comment ‘foreach o in obserers’ which implies all registered observers get updated.

Code

Full code can be downloaded from here.

I created the simple example of Observer Pattern with the concept of football game. I have used event for registering/unregistering observers. I have used events for registering/unregistering observer.

I created an IPerson interface which is our observer. It is the one which is registered to the subject.


public interface IPerson

{

void UpdatePosition();

Position Position { get; set; }

}

And our subject is the Ball abstract class. It is abstract because I think I can extend it to any other balls like FootBall, VolleyBall etc. It has the AttachObserber and DettachObserver functions which registered and unregistered the observer. Whenever there is change in the position of the ball, it uses Notify function to notify all registered observers.


public abstract class Ball
{
public Ball(double size, string color)
{
_size = size;
_color = color;
_persons = new List(0);
}

public void AttachObserver(IPerson person)
{
_persons.Add(person);
_positionChanged += person.UpdatePosition;
}

public void DettachObserver(IPerson person)
{
_positionChanged -= person.UpdatePosition;
_persons.Remove(person);
}

public void DettachAll()
{
foreach (IPerson p in _persons)
_positionChanged -= p.UpdatePosition;
_persons.Clear();
}

public Position Position
{
get { return _position; }
set
{
_position = value;
Console.WriteLine("Current football position: {0}, {1}", _position.XPos, _position.YPos);
NotifyPlayers();
}
}

public void NotifyPlayers()
{
if (_positionChanged != null)
_positionChanged();
}

private Position _position;
private double _size;
private string _color;
private List _persons;
private NotifyBallObserverEventHandler _positionChanged;
}

Conclusion

Observer defines a much decoupled interface that allows for multiple receivers to be configured at run-time. Mediator pattern also provides the mediator object which encapsulates the communication between objects. But observer provides the different mechanism where all observers get updated when subject changes.

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.