Monday, July 30, 2007

Observer pattern : broadcast the message

Hi,
Am back with a new post.
today we can focus on a new design pattern- "Observer pattern".

let us consider this scenario -
we have a candidate, who wants to get a job. The candidate informs a Job Consultant about this.

design -
we can design this in two ways
1) the candidate goes to the job consultant very often and then gets the status from him (this is nothing but polling)
2) the Job Consultant comes to know when there is a vacancy and then informs all the people for whom he is consulting. (this is broadcast)

disadvantage with option 1 is that some classes have to poll and polling takes a very long time.
even in the real life scenario, the candidates would not prefer to go to the consultant every "now and then" just to get the status neither would the consultant like being disturbed.
so both the candidate and the consultants would prefer option 2.

This is our observer pattern.
we have a an observer class (in our case "JobConsultant") which maintains a list of all the subjects which it is going to observe (here the subject is the "candidate").
All the subjects have to subscribe to the Observer;the subject can also unsubscribe; this is similar to a magazine subscription mechanism.

the observer will broadcast a message to all the subjects subscribed (just like our newspaper vendors).




using System;
using System.Collections.Generic;
using System.Text;

namespace ObserverPattern
{
public interface IJobConsultant
{

void Subscribe(Icandidate candidate);
void UnSubscribe(Icandidate candidate);
void OnVacancy();
}
public class JobConsultant : IJobConsultant
{
System.Collections.ArrayList Candidates;

public JobConsultant()
{
Candidates = new System.Collections.ArrayList();
}
public void UnSubscribe(Icandidate candidate)
{
Candidates.Remove(candidate);

}
public void Subscribe(Icandidate candidate)
{
Candidates.Add(candidate);
}

public void OnVacancy()
{
foreach (Icandidate Obj in Candidates)
{
Obj.notify();
}
}

}

public interface Icandidate
{
void notify();
void unSubscribe();
}

class candidate :Icandidate
{
string CandidateName;
IJobConsultant jobConsultant;
public candidate(string Name, IJobConsultant pjobConsultant)
{
CandidateName = Name;
jobConsultant = pjobConsultant;
jobConsultant.Subscribe((Icandidate)this);
}

public void unSubscribe()
{
jobConsultant.UnSubscribe(this);

}
public void notify()
{
Console.WriteLine("vacanacy created "+ CandidateName);
}
}
}


so now our classes and interfaces have been developed, we need to invoke this .
we can invoke this using the following the code:

IJobConsultant ObjJobConsultant = new JobConsultant();
candidate can1 = new candidate("candidate1", ObjJobConsultant);

ObjJobConsultant.OnVacancy();

what is the output?
the output will be

vacanacy created candidate1

Decorator pattern : Add functionality by wrapping

Hi,

I am back with a new pattern today.

My requirement is to create a game which simulates with a pizza store.Right now the store will support two type of Pizzas "Cheese" and "DoubleCheese". So i start off with the design, i will have a class called "Pizza" which has the cost and description of the Pizza.Now we will have to have two more classes "Cheese pizza" and "doubleCheesePizza". both of them extend the "Pizza" class. this will work fine- no problem. but after all this , now i feel that my pizza store has to have some more pizzas. so I have to introduce new classes for the new pizzas. so the problem is something called "Class Explosion" - having a lot of classes which finally become unmanageable. Some of the classes will be

Cottage garden, cottage garden with extra Cheese, papperoni, papperoni with extra cheese so on.

but now if i want to introduce pizzas with thin crust? we are all lost, we have to make such a lot of changes in the design. My pizza store will be limited in terms of the pizza it offers. competitors will offer a lot of variety and one fine day i will have to close my store.

this is the piece of code (This is wrong design)

public class Pizza

{

double _Cost;

string _Description;

public double Cost

{

set

{

_Cost = value;

}

}

public string Description

{

set

{

_Description = value;

}

}

public void GetCost()

{

Console.WriteLine("The Cost is " + _Cost.ToString());

}

public void GetDescription()

{

Console.WriteLine("The Description is " + _Description);

}

public Pizza()

{

}

}

public class CheesePizza : Pizza

{

public CheesePizza()

{

}

}

public class DoubleCheesePizza : Pizza

{

public DoubleCheesePizza()

{

}

}

public class CottageGarden : Pizza

{

public CottageGarden()

{

}

}

Method of instantiation

Pizza obj = new Pizza();

obj.Cost = 150.00;

obj.Description = "pizza base";

obj.GetCost();

obj.GetDescription();

Pizza obj1 = new CheesePizza();

obj1.Cost = 190.00;

obj1.Description = "pizza base with cheese";

obj1.GetCost();

obj1.GetDescription();

But I feel that there is another nice manner in which we can implement the same. how? lets start with the "design principles" -

1) identify what changes and what remains static - here the crust (i sometimes use the term "type of pizza" for the same) and the topping (flavor of pizza) change, so we need to differentiate them.

2) code to interface not to an implementation (so we need some abstract classes or interfaces here)- we will have a common abstract class for pizza crust called "Pizza", why abstract class? because we have the properties - cost and description. interfaces cannot have properties. we have two functions :getCost() and GetDescription() which are abstract methods. We have two classes - "ThickCrust" and "ThinCrust" implements "Pizza". we now focus on the topping - we have a abstract class topping which extends pizza ( why extend pizza? topping will not be used by itself, it will always be a part of pizza an addon to pizza.). now we have some topping (cheese ) to add flavor to the crust. we implement the methods of "Pizza" in these classes. also these class will have an object of type "Pizza". why?reason is that we are adding something more to the basepizza. we have a pizza crust, we add one topping to that crust, then we can add one more topping to the pizza which we have now. that is the reason why we have pizza composed as a part of topping (cheese and double cheese).


example

thin crust is a pizza.

this if contained with in a cheese object will be (thin crust + cheese) which is again a pizza.

if (thin crust + cheese) is in another cheese object (it is again a pizza - a double cheese).

so now we don't need the double cheese class itself. can e see the difference between our old approach and our new approach-- yes we can drastically reduce the number of extra classes.


public abstract class Pizza

{

public double Cost;

public string Description;

public abstract Double getCost();

public abstract string GetDescription();

}

public class thinCrust : Pizza

{

public thinCrust()

{

this.Cost = 160;

this.Description = "thin Crust ";

}

public override double getCost()

{

return this.Cost;

}

public override string GetDescription()

{

return this.Description;

}

}

public class thickCrust : Pizza

{

public thickCrust()

{

this.Cost = 140;

this.Description = "thick Crust ";

}

public override double getCost()

{

return this.Cost;

}

public override string GetDescription()

{

return this.Description;

}

}

public abstract class Topping : Pizza

{

}

public class Cheese : Topping

{

Pizza PizzaObject;

public Cheese(Pizza pPizza)

{

PizzaObject = pPizza;

}

public override double getCost()

{

this.Cost = PizzaObject.Cost + 20;

return PizzaObject.Cost +20;

}

public override string GetDescription()

{

this.Description = PizzaObject.Description + " , Cheese topping";

return PizzaObject.Description +" , Cheese topping";

}

}

To instantiate

create a crust (thin or thick) object first,

wrap it in the topping object (cheese as of now). this will create a cheese pizza. now we can wrap this cheese pizza in another cheese object and the result will be a double cheese pizza.

Pizza objPIzza = new thickCrust();

Pizza Objcheese = new Cheese(objPIzza);

Console.WriteLine(Objcheese.getCost());

Console.WriteLine(Objcheese.GetDescription());

//implementing double cheese

Pizza DoubleCheese = new Cheese(Objcheese);

Console.WriteLine(DoubleCheese.getCost());

Console.WriteLine(DoubleCheese.GetDescription());

Output

160

thick Crust , Cheese topping

180

thick Crust , Cheese topping , Cheese topping


can you see how flexible our design is now?

if i want my store to introduce a new type of pizza ( say a new crust -- UltraThinCrust) and a new topping (called "Extravaganza"), i have to create a new class "UltraThinCrust" which implements "Pizza" and a new class called "Extravaganza" which implements "Topping" and then i can create an instance of "UltraThinCrust" and pass it to an instance of Extravaganza.

so we get a new pizza "UltraThinCrust Extravaganza".

no class explosion, no unmanageable classes.

its all easy by just wrapping objects.


Happy Coding !!!



Virtual functions


Hi all,

i am back with another post.but this post is not about design patterns,but it is about one of the most trivial but important features of C# - virtual functions.
let me explain the theory first and then we can look into one example.

Inheritance is one of the most important aspects of Object Oriented Programming. the purpose of inheritance is to reuse the functionality and also to extend the functionality offered by the base class.

consider the example given below


namespace virtualFunctions

{

class baseClass

{

int i;

public baseClass()

{

}

public baseClass(int val)

{

i = val;

}

public void Add()

{

Console.WriteLine(i);

}

}

class DerivedClass : baseClass

{

int j;

public DerivedClass(int val)

{

j = val;

}

public void Add()

{

Console.WriteLine(j+20);

}

}

}

Now call will be like this

baseClass b = new DerivedClass(20);

b.Add();

output is 0 coz the Add() function of the baseclass is called.

reason : we are calling the Add() method using the baseclass object. So the Add() of the baseClass is called.

Modify the baseclass function to

public virtual void Add()

{

Console.WriteLine(i);

}

And the derived class function to

public override void Add()

{

Console.WriteLine(j+20);

}

C all using the same invoking call usedpreviously.

The output is 40 coz the derivedclass’ Add() Function is called because of using the virtual keyword.


Now the output is 40. why? because the function is virtual, the Add() method of the DerivedClass is called even if we call the Add() method using the BaseClass instance.

This is because when we have declared the function as virtual and overriden it.

so when we create a n instance of DerivedClass and then assign it to a baseclass object,

the runtime instance is considered when the Add() function is called.

Hope this helps us all to understand virtual functions better.

happy Coding!!!




Wednesday, July 25, 2007

Strategy pattern : Algorithm on the Fly

hi,
i am back with another pattern. Today we will discuss about "Strategy Pattern".

consider this scenario : i want to develop a game which has soldiers fighting.
right now i have only one soldier "SharpShooter". but i would like to enhance the game by including some more soldier types. how we go about the design?
well the first thing which we all think of is reuse. so we develop a single class called "Soldier", then we extend ( inherit) this class in other classes.

the code for this will be

public class Soldier
{
public Soldier()
{
}

public virtual void FightEnemy()
{
MessageBox.Show("I am fighting");
}
}

the FightEnemy is a simple function in this case, but i plan to add functionality here once i find out what the game character has to do.

now i have the SharpShooter Class which will extend Soldier

public class SharpShooter : Soldier
{
public SharpShooter()
{
}
public override void FightEnemy()
{
MessageBox.Show("I am shooting Bullets");
}
}

but the disadvantage with this problem is the method has to be overridden in the derived classes.
why? i will tell you the answer

consider an unconscious soldier who will never be able to fight,the class will be:

public class UnconsciousSoldier : Soldier
{
public UnconsciousSoldier()
{
}

}

but when you call :

Soldier s = new UnconsciousSoldier();
s.FightEnemy();

the soldier starts fighting and the message box "I am fighting" pops up.
so we have to make sure that we override the FightEnemy() in all the derived classes of Soldier.
but don't you think this is a little too much?
if i forget overriding, then the soldier, even if dead, starts fighting ( i don't want lord of the rings here where we have UnDead) .

but i have a much more easy to use solution:

we apply the design principle :
"separate whatever varies and encapsulate them"
here the fighting behavior varies.

we will take the fighting behaviors and then separate them from the class.
for this we will have an interface called IFightBehaviour :

interface IFightBehaviour
{
void Fight();
}

now we apply another design principle
"Program to an interface not to an implementation".

So we will have the soldier as an interface, not as a class :

interface ISoldier
{
void FightEnemy();
}


we will introduce new fighting behaviors now. how do we do it?
we just implement the IFightBehavior interface :

class SharpShoot : IFightBehaviour
{
#region IFightBehaviour Members

void IFightBehaviour.Fight()
{
MessageBox.Show("Shooting Bullets");
}

#endregion
}


class DeadSoldierBehavior : IFightBehaviour
{
#region IFightBehaviour Members

void IFightBehaviour.Fight()
{
MessageBox.Show("Cannot fight,so do nothing");
}

#endregion
}



now we will apply another design principle :
"Has a is better than is a". what does this mean? "composition is better than inheritance".
so the fightbehaviour will be a part of the Soldier classes :

class SharpShooter : ISoldier
{
IFightBehaviour FightBehaviour;


public SharpShooter(IFightBehaviour pFightBehaviour)
{
FightBehaviour = pFightBehaviour;
}
public void FightEnemy()
{
FightBehaviour.Fight();
}
}


now IFightBehaviour is a part of SharpShooter class.

now we instantiate SharpShooter like this :

IFightBehaviour FightBehaviour = new SharpShoot();
SharpShooter shooter = new SharpShooter(FightBehaviour );
shooter.FightEnemy();

now in case of dead Soldiers, we will have need not have another class,
we can modify the same class with a new fightbehaviour. how is this? i will explain

consider the code given below

IFightBehaviour FightBehaviour = new DeadSoldierBehavior ();
SharpShooter shooter = new SharpShooter(FightBehaviour );
shooter.FightEnemy();

(DeadSoldierBehavior is a class implementing IFightBehavior which denotes what a dead soldier has to do)
the above code snippet will print
"Cannot fight,so do nothing",which was coded in the FightEnemy() function of "DeadSoldierBehavior " class.

so we can change the behaviour of the the class at runtime. How?

simple, consider the snippet below :

IFightBehavior FightBehavior;
//if soldier is alive and is a shooter

FightBehavior = new SharpShoot();
SharpShooter shooter = new SharpShooter(FightBehaviour );
shooter.FightEnemy();

//elseif the soldier is dead

FightBehavior = new DeadSoldierBehavior ();
SharpShooter shooter = new SharpShooter(FightBehaviour );
shooter.FightEnemy();



i want to add a new behavior like- say a demolition specialist, all i need to do is create a new Fightbehavior class implement IFightBehavior in this class and implement Fight() function to suit a demolition expert.
and the rest is all the same: create an instacne of demolitionFightbehavior class and apss it as a parameter to SharpShooter class and call the FightEnemy().

when do we need to use Strategy pattern?
when we want to change behaviors on the fly (at runtime).
or
when we want different algorithms to be executed at the fly.

we could have done it using several if else, switch case etc.
but just how managable and maintainable would that be?
and the most important of all would it be flexible? no not at all.
just look at the code which we have now?
we have just a few classes but look how flexible the design is.
we can add a new functionality with less modifications to the existing classes.
we strictly follow the "open close" principle here :
A design should be open for extension but closed for modification.

this is the strategy pattern.

happy coding !!!

regards,
nandan

Tuesday, July 24, 2007

singleton - the simpleton

hi,
In my last post, i spoke of design patterns and their importance.
now we can start discussing about the different design patterns and teh scenarios where we can use them.
i don't want to get into the details of separating the design patterns based on behavior ,creation etc.
we can just discuss the design patterns here.

the simplest of all the design patterns is "singleton".

lets consider this scenario. we are developing a game ( car race, of course). we have the car object.
but car object is a composite object which is composed of several other objects like wheels,steering,seat, window, brake,accelerator,clutch,gear etc.
steering is a class which looks like this

Interface Isteering
{
public void TurnLeft();
public void TurnRight();
}

public class Steering :ISteering
{
public Steering()
{

}

//we will haev to implement TurnLeft and TurnRight methods here
}

now steering will be called from the car class like this

steering CarSteer = new Steering();

but the flaw with this is that we can create the steering class even in the window class, as this would lead to two steering objects. one from the car and one from the window.
but we have a means to resolve this problem.

consider the code given below( i have modified the steering class)

public class Steering :ISteering
{
static _SteeringObject;

public static Steering GetSteering()
{
if(_SteeringObject == null)
{
_SteeringObject = new Steering();
}
return _SteeringObject;
}
private Steering()
{

}

//we will haev to implement TurnLeft and TurnRight methods here
}

and all the obejcts which want to access the steering object will cal the function like this

Steering objSteer = Steering.GetSteering();

the advantage of this is that there is a single instance of steering created and that instance will be accessed from any other class be it window or car class.

can we think of some other singleton patterns in the car class?

yes of course we can:

brake, accelerator,handbrake etc are all singletons.
we can discuss some other design pattern in my next post.

regards,
nandan

Thursday, July 19, 2007

Introduction to Design Patterns

one of the most important aspects of software development is that the developed software must be very much extendable without causing critical problems and also it should be easily maintainable.

but not many of us focus on developing a software keeping these two aspects in our mind. we just plan to meet the deadline and somehow get the software working according to customer requirements. But little do we realize that once the customer changes his requirement a little or plans to extend his software requirement, then we will have a hell of time in changing our code.

this in turn will become a cycle. we spend such a lot of time reworking on the same thing even for some minor change in the requirement.

enter design patterns and design principles, these two will reduce the "one hell of a time" which we are spending here and lets us focus on other important things like quality and testing.

what exactly are design patterns and principles?
we all know About the software development life cycle. we know how important design is in the development of a software. one small mistake and the whole software is in the docks.
so we will have to be very careful in design phase.
but this is the phase where in we can never recognize that we are going wrong.
this phase requires a long foresight into the problem which may be faced in the future. we should design in such a way that we can always add new features to the software without modifying the existing design and then adding some new design to the existing design(this is known as "open close principle").

design patterns and principles do enable the same. these are the guidelines which have been identified by many design gurus. people have made some mistakes in the past about designing a software and later realized that they were going wrong, but they also found out that there are some common solutions which can be followed for such design problems and so evolved design patterns and design principles.

but one thing which we all have to remember is that design patterns should not be used to impress people, it has to be used to make software maintainable.
it really does not make sense to use all the design patterns in design if they are not really needed.

so lets make sure that we use these to the fullest extent and with proper discretion and make our software design extendable.

wait for my posts on specific design patterns.

The problems for which the design patterns are used are also unique.