Thursday, December 6, 2007
Composite pattern
am back after a long time :)
today its a new design pattern.
scenario
i want to design a graphic engine which has a graphic surface and this surface renders many graphic images like lines,rectangles etc.
so where do we start?
we will have an interface IGraphic (methods - AddControl,RemoveControl,getControls)
this is implemented by a a class Graphic
public class Graphic :IGraphic
{
//implement the methods here
//also this class will compose of IControl - which are implemented by control class
}
this is fine.....
i am happy and the software works fine.....until one da ,when the customer comes back to me ..he says that he wants controls to host other controls...he wants the graphic surface to host controls and these controls may contain other controls.
so now how will i incorporate this?
am i stuck ?
well as a matter of fact,i am in a litle bit of a soup.
i can somehow manage for the particular control the cutomer says as of now.
but if he comes back tomorrow for another control, i am lost again :(.......
wel lbut now i know of these problems, why not change the intial design itself to incorporate all the changes the customer asks for?
how? have a look below
IGraphic can be an abstract class.
public abstract class IGraphic
{
public void AddChild();
public void RemoveChild();
public arraylist getChildren();
}
public class Graphic :IGraphic
{
//implement the methods of the base class here
//have an arraylist of child objects
//so it will be
arraylist Children;
}
public class GroupBox : IGraphic
{
//implement the methods of the base class
//have an arralist of the children
arraylist children;
}
public class Button:Igraphic
{
//provide dummy implementation here for addchild , getchildren and removechild as
//this control does not have children
}
example code is given below
public abstract class IGraphic
{
protected System.Collections.ArrayList Children;
string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public abstract void AddChild(object obj);
public abstract void removechild(object obj);
public abstract System.Collections.ArrayList getChildren();
public void print()
{
Console.WriteLine("Name is "+Name);
}
}
public class graphic : IGraphic
{
public graphic()
{
Children = new ArrayList();
}
public override void AddChild (object obj)
{
Children.Add(obj);
}
public override void removechild (object obj)
{
Children.Remove(obj);
}
public override System.Collections.ArrayList getChildren()
{
return Children;
}
public void print()
{
Console.WriteLine("Name is "+Name);
foreach(object obj in Children)
{
Console.WriteLine("children are " + ((IGraphic)obj).Name);
}
}
}
public class Groupbox : IGraphic
{
public Groupbox()
{
Children = new ArrayList();
}
public override void AddChild (object obj)
{
Children.Add(obj);
}
public override void removechild (object obj)
{
Children.Remove(obj);
}
public override System.Collections.ArrayList getChildren()
{
return Children;
}
public void print()
{
Console.WriteLine("Name is "+Name);
foreach(object obj in Children)
{
Console.WriteLine("children are " + ((IGraphic)obj).Name);
}
}
}
public class Button : IGraphic
{
public Button()
{
}
public override void AddChild (object obj)
{
//do nothing
}
public override void removechild (object obj)
{
//do nothing
}
public override System.Collections.ArrayList getChildren()
{
//do nothing
return null;
}
public void print()
{
Console.WriteLine("Name is "+Name);
}
}
static void Main(string[] args)
{
graphic g = new graphic();
g.Name = "graphic object";
Groupbox gbox = new Groupbox();
gbox.Name = "Groupbox";
Button b = new Button();
b.Name = "button inside the groupBox";
Button btn = new Button();
btn.Name = "button inside the graphic";
gbox.AddChild(b);
gbox.print();
g.AddChild(gbox);
g.print();
g.AddChild(btn);
btn.print();
g.print();
}
output is
Name is Groupbox
children are button inside the groupBox
Name is graphic object
children are Groupbox
Name is button inside the graphic
Name is graphic object
children are Groupbox
children are button inside the graphic
Tuesday, November 27, 2007
WCF
I will discuss about what WCF is a little later on. But now we will have to summarise how two different Applications can interact with each other. We have remoting which allows two different applications in different application domains to interact with each other. We have MSMQ using which two different applications can pass messages between them. We have WebServices using which we can make two applications interact.but all these have some shortcomings. For exampleMSMQ will be able to run on only windows machines.two applications have to conform to some specific standards if they have to use web services. Remoting will be possible only if both the applications are written in dot net.so to over come all these shortcomings, microsoft has come up with a new set of APIs to enable communication. This is Windows Communication Framework.
This is similar to web services (Service Oriented Architecture) , but WCF is flexible and its core serivices can be extended to suit our needs.so as industry standards grow, we can extend the WCF core.
WCF can operate with various things like MSMQ,Pipes, HTTP etc. This will be released with dot net framework 3.0 and orcas.
So without further delay we will develop a sample to enable us to understand better.
Create a new project of type “WCF service Library”
A class and a interface are created by default, delete them off. Also we have to add the following two “using statements” and references to “System.ServiceModel”
Using System.ServiceModel
Using System.Runtime.Serialization
Now we will start coding our custom interface and then implement taht interface.
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Add(int val1,int val2);
}
Here, the ServiceContract attribuite specifies that the interface is the contract for the service. Not getting it? Ok ,WCF works on 3 basic principles : ABC, address,binding ,contract. If you know COM, you will know that we have an interface to specify the service provided. And then we use QueryInterface on the Factory class to get that interface (type casted object). This is nothing but contract. So IMathLIB is the service contract which we will be exposing (C of WCF). Now the other Attribute is “OperationContract”- this signifies that the operation is being exposed by the service.now we have to implement this interface :
public class MathService : IMathLIB
{
public int Addint(int val1,int val2)
{
return val1+val2;
}
}
Now we have a MathService class which implements IMathLIB.build this , a DLL is generated..lets name it as MathService.
Now is this enuf? No not at all..all we have doen is just created a service. Now we have to host that service in some other application and run that host application. This forms the server part of WCF. Then we have t ocraete a client to consume this service.
Creating the server is simple :
Create a simple cnsole application projecct and name it as MathServiceHost, add a refrence to “System.ServiceModel”, “System.IdentityModel”, and “System.Runtime.Serialization”. now add a reference to “MathService.dll”.
Now we will start coding for the host
internal class MathServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8000/MathService");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(MathService), new Uri( "http://localhost:8000/MathService"));
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
Now add config file :
contract="MathServiceLIB.IMathLIB"
binding="basicHttpBinding"/>
Look at the address, binding and contract in the config file.it completes the jigsaw puzzle,does i t not?
Build this and it builds without any errors. So this is fine.
Now to develop a client :
Just create a simple console application named “MathClient” and then add a “service refrence “ this the URL specified in the address in the config file (shown above) and then we can use the service just like we use web services. bingo-- that does it.
But what if we want to add a new class in the service ? can we have operations on that class?
Well, we can!!!!
How? I will tell you .
Change your IMathLIB as shown below
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Addint(int val1,int val2);
[OperationContract]
DataContract1 Add(DataContract1 dataContractValue,DataContract1 dataContractValue2);
}
And then ad the new class type which you want
[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public DataContract1 Add(DataContract1 data)
{
DataContract1 dc = new DataContract1();
dc.FirstName = this.firstName + data.FirstName;
dc.LastName = this.LastName + data.LastName;
return dc;
}
}
The attribute DataContract specifies that it is a datatype and the atribute “Datamember” specifies that it is a field.
Now w can code for our MathService class and implement the IMathLIB interface.
The rest is all as we did before
Hope this helps u.
Happy Coding !!!
Regards,
nandan
Sunday, November 18, 2007
Command Pattern
we will discuss about command pattern today !!!
scenario :
i am developing a game where i have my main character running,sitting and standing.
for now , will print "sit" when he sits,"stand" when he stands,"run" when he runs.
how do we go about this?
simple solution which falshes on to our mind right now is
1)develop and enum haveing its members as run,sit and stand.
2) in the user class,have this enum.
3) when any command is performed on the user handle it in a function called ExecuteCommand. In this function have an if loop and check for the enum.
voila, we get the output !!!!
so where is the problem?
well, my character is still evolving in the game. so now i identify a new scenario where the character has to sleep.so, i have to modify the user class by adding a new new enum "sleep" and then modify the if condition.....dont you think this is bad????
tomorrow i can identify some new user actions, then again i have to modify this?
naaah..this will not do...
how can we do a proper design for this?
this is where we use the command pattern.
in this pattern we make each and every user action as a class.and this class will handle its own command and perform the action necessary.
i mean " encapsulate a command into an object".
see the example below
public interface ICommand
{
void Execute();
}
public class RunCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Run Command executed");
}
#endregion
}
public class StandCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Stand Command executed");
}
#endregion
}
public class User
{
public void Action(ICommand cmd)
{
cmd.Execute();
}
}
and when i call this:
User Character = new User();
ICommand cmd = new RunCommand();
Character.Action(cmd);
so i create an instance of the command needed and pass it on to the Action function.
and then the class (command class) performs the necessary action.
now of i want to add a new command - sleep?
all i need to do is create a new class called Sleep,implement ICommand.
then implement the function Execute.
a new action has been introduced.
not if i want the user ot perfrom this :
ICommand SleepCmd = new SleepCommand();
Character.Action(SleepCmd);
this will perform the necessary action.
HAPPY CODING!!!!
regards,
nandan
Thursday, November 15, 2007
FacadePattern - a centralised controller
been a long time since my last post eh?
sorry for that.
we shall discuss about a new design patter ntoday - Facade pattern
what exactly is a facade pattern?
technically speaking, it is a class which controls many other classes.something like a manager class.
let us take up a simple scenario :
i want to watch a movie at home..what all do i do?
1) i turn on the TV.
2) i turn on the speakers.
3) i turn on the DVD player
4) i turn off the lights
ok..so i have a class called user (that is me) which has to create instances of TV,DVD,Speakers,Lights and then on each of them call the start method. to switch off also its exactly same- we call the stop method. this is fine..no issues with this manner. but think of the user class, it has to maintain object references to the 4 classes. the user class may be very huge in itself. so we are increasing the burden on the user class. now if i have to have another class which has to perform the same 4 steps, tehn i have to have instances of these 4 classes again. and any new step included will change all the classes which perform these 4 steps.
so how can we make this more easier to manage? we will introduce a manager class in between..in this case "Remote" class.this will handle all the other 4 classes and perform the necessary steps.This is teh facade class.
advantages of using facade pattern are
1) the class (user class) which had to perform all the steps is not overloaded.
2) all the steps are maintained in a central location (Remote class).
look at the code sample below :
public interface IFacadeObject
{
void Start();
void Stop();
}
public class Remote : IFacadeObject
{
IFacadeObject DVDobj,SpeakerObj,LightObj,TVObj;
public Remote()
{
DVDobj = new DVD();
SpeakerObj = new Speakers();
LightObj = new Lights();
TVObj = new TV();
}
#region IFacadeObject Members
public void Start()
{
Console.WriteLine("Remote switched on");
TVObj.Start();
DVDobj.Start();
LightObj.Start();
SpeakerObj.Start();
}
public void Stop()
{
Console.WriteLine("Remote switched off");
TVObj.Stop();
DVDobj.Stop();
LightObj.Stop();
SpeakerObj.Stop();
}
#endregion
}
public class TV : IFacadeObject
{
public TV()
{
}
public void Start()
{
Console.WriteLine("TV switched on");
}
public void Stop()
{
Console.WriteLine("TV switched off");
}
}
public class AirCondition : IFacadeObject
{
public AirCondition()
{
}
public void Start()
{
Console.WriteLine("AirCondition switched on");
}
public void Stop()
{
Console.WriteLine("AirCondition switched off");
}
}
public class Speakers : IFacadeObject
{
public Speakers()
{
}
public void Start()
{
Console.WriteLine("Speakers switched on");
}
public void Stop()
{
Console.WriteLine("Speakers switched off");
}
}
public class DVD : IFacadeObject
{
public DVD()
{
}
public void Start()
{
Console.WriteLine("DVD switched on");
}
public void Stop()
{
Console.WriteLine("DVD switched off");
}
}
public class Lights : IFacadeObject
{
public Lights()
{
}
public void Start()
{
Console.WriteLine("Lights switched off");
}
public void Stop()
{
Console.WriteLine("Lights switched on");
}
}
This is our classes.
so when we call the "Remote" class instance, it will be doing all the necessary steps.
the call is made from the user class in this manner :
IFacadeObject RemoteObj = new Remote();
RemoteObj.Start();
Console.WriteLine("Things are working now ");
RemoteObj.Stop();
the output for this is
Remote switched on
TV switched on
DVD switched on
Lights switched off
Speakers switched on
Things are working now
Remote switched off
TV switched off
DVD switched off
Lights switched on
Speakers switched off
happy coding !!!!
regards,
nandan
Thursday, October 11, 2007
how to use NUnit for Test Driven Development(TDD)
i had spoken about TDD in one of my earlier posts.
now we can discuss about using some unit testing tools for TDD.One of the most common tools used is NUnit. the class which i want to test is a class which performs some basic math operations like add,subtract,divide and multiply.
the code for the class is as shown below
using System;
using System.Collections.Generic;
using System.Text;
namespace BasicMaths
{
public class Math
{
public Math()
{
}
public int Add(int i, int j)
{
return i + j;
}
public int Subtract(int i, int j)
{
return i - j;
}
public int Multiply(int i, int j)
{
return i * j;
}
public int Divide(int i, int j)
{
if(!CheckZero(j))
return i / j;
return 0;
}
public bool CheckZero(int i)
{
return( (i==0)? true:false);
}
}
}
now we have to give this class to some other component for consumption. But before that we have to make sure that each and every operation in this class works fine. For that we either have to write test stubs using NUnit. when we write a test class using NUnit we have to add NUnit.Framework.dll as a reference.Then we have to write the Test class.
As shown in the code below, the Class has to have an Attribute called [TestFixture], this is to convey to the compiler that the class is used for testing purpose. and each method which is used for testing should have the attribute [Test] to convey that the method is actually a NUnit test method.
we will build this project. a DLL will get created as a result. go to the folder where NUnit is installed. Run the file NUnit-GUI.exe. in this application, go to file->load rojet and then select the basicMathsTester.dll.
The DLL is loaded and all the classes along with their member functions are listed.
select on any function and click on the button run. If the method passes, then there will be aprogress bar in green color, else in case of failure the progress bar will be red in colour.
Monday, September 3, 2007
Bridge Pattern
Another new post today :)
scenario :
I have a car factory which manufactures cars.
I have few models of cars which use petrol as fuel. So the design for this will be an interface ICar which is implemented by cars. So the names of these car classes are : ToyotaPetrol, SuzukiPetrol etc. until now i have a flexible manufacturing unit i can introduce new cars any time i want. but now market changes, my competitors also do the same. So i think of introducing new cars which run on diesel as well. so how do i go about this? add new classes : ToyotaDiesel, SuzukiDiesel. is this right? no..not at all...reason being : to introduce any new car, i will have to add two classes : one for petrol and one for diesel. can this be eliminated? yes.
how?
separate the Fuel and the car and then have some method to change the fuelling mechanism for the car object. this is know as Bridge pattern
bridge pattern says : separate the abstraction from it implementation.
look at the code below :
public abstract class ICar
{
protected IFuel _Fuel;
public void SetFuel(IFuel Fuel)
{
_Fuel = Fuel;
}
public abstract void Print();
}
public class Toyota: ICar
{
public override void Print()
{
Console.Write("Toyota with ");
_Fuel.Print();
}
}
public class Suzuki: ICar
{
public override void Print()
{
Console.Write("Suzuki with ");
_Fuel.Print();
}
}
public interface IFuel
{
void Print();
}
public class Petrol : IFuel
{
public void Print()
{
Console.WriteLine("Petrol");
}
}
public class Diesel : IFuel
{
public void Print()
{
Console.WriteLine("Diesel");
}
}
method of invoking :
ICar objcar = new Toyota();
IFuel objFuel = new Petrol();
objcar.SetFuel(objFuel);
objcar.Print();
so the fuel and car are very much separate now.
i can change the fuelling machanism by calling the setFuel() method.
When i initially got to know about this pattern, i mistook this to be like the decorator pattern. actually both are different. Bridge separates the abstraction and implementation (as seen with the car and fuel) but decorator wraps an object inside another object in turn adding more functionality to the object.
happy coding !!!
Friday, August 24, 2007
Template Method : template for execution
a new pattern today :)
scenario:
i have some classes to create pizzas (back to pizzas eh!! :) ). my cousin baked some pizzas at my place,so i do know the steps :).
so the steps are
1) use the pizza base.
2) Add toppings.
3) add sauce
4) bake
So now i have an interface IPizza:
public Interface IPizzaManufacture
{
void UsePizzaBase();
void AddToppings();
void AddSauce();
void Bake();
void createpizza ();
}
now the Pizza manufacture classes implement this interface
public Class LargeCheesePizzaManufacture :IPizzamanufacture
{
public void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public void AddSauce
{
Console.Writeline("Add Tomato sauce");
}
public void AddToppings
{
Console.Writeline("Cheese Toppings");
}
public void bake()
{
console.WriteLine("Baking now");
}
}
now if i add another class called largePapperoniPizza, i will have to implement all the methods.
nothing wrong with this.
but i notice that i will have to implement the createpizza method for every class i add, even though i dont want to introduce any new createpizza behaviour.
so 20 classes added, 20 times i implement the createpizza() method. can we avoid this?
absolutely yes:
find out the method which will remain common --now it is createpizza().
we will change the interface to an abstract Class
public Abstract Class IPizzaManufacture
{
public abstract void UsePizzaBase();
public abstract void AddToppings();
public abstract void AddSauce();
public abstract void Bake();
public virtual void CreatePizza()
{
UsePizzaBase();
AddToppings();
AddSauce();
Bake();
}
}
now i will implement this abstract class in many other classes.
public Class LargeCheesePizzaManufacture :IPizzamanufacture
{
public override void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public override void AddSauce
{
Console.Writeline("Add Tomato sauce");
}
public override void AddToppings
{
Console.Writeline("Cheese Toppings");
}
//no bake method here
//i will use the createpizza method of the abstract class
}
but notice that i will not have to implement the createpizza () method unless i want to add a custom createpizza () functionality.
public Class LargeVegetablePizzaManufacture :IPizzamanufacture
{
public override void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public override void AddSauce
{
Console.Writeline("Add Tomato and garlic sauce");
}
public override void AddToppings
{
Console.Writeline("Vegetable Toppings");
}
//i will use the a custom createpizza mechanism
public override void createpizza ()
{
Console.writeLine("createpizza for a long time");
}
}
so the createpizza () method acts as a template.
this is known as Template method because this method will create a template for execution.
happy coding !!!
Wednesday, August 22, 2007
Iterator pattern
long time since my last post :( sorry.
today i will be discussing about a new pattern
scenario :
i want to list all the cars and two wheelers in my locality.i have two classes "cars" and "bikes". but instead of cosing for these classes, i have asked two of my friends to code. they have done a commendable job,everything implemented and works properly. but now, the problem is one of the classes return the list in the form of an arraylist and the other in the form of array.
example :
public arraylist GetCars()
and
public object[] GetBikes()
my friends have given me their code. i have to use it. i will have a difficulty using them cause i will have to use arraylist in one instance and object[] in another. For arraylist, i can use foreach, but for array, i will have to use for loop.
if both of them were somewhat similar, i could have used a generic function to get the objects from the list. But lets get back to reality, both of them are different. how do i manage? do i change the arraylist in one of the classes to array type so that i can use the generic method? or do i change the array to arraylist?
let us think - is it really necessary to change the data structure used to store the data? is it not a complicated change? i really do not know the logic which my friends have used.
is there any other possibility?
yes, there is!!!
the Iterator pattern is the answer.
i will have an interface called iIterator which looks like this
public interface iIterator
{
bool MoveNext();
object getCurrent();
}
and the classes car and twowheeler impements this interface.
MoveNext() will return true/false based on whether the array / arraylist has an object in the next position and moves the cursor to the next position.
getCurrent() will return an object from the current cursor location.
what i did was instead of returning the arraylist/array from the class, i return each individual object and then move the cursor to the next location.
this will be clear if we look into the example for the class which has arraylist.
public class Cars : iIterator
{
private int Cursor = 0;
Arraylist Cars = new Arraylist();
//-----------------------------------------
//the code for filling up the arraylist goes here
//lets not get into it as we are aware of how this is done
------------------------------------------//
public object getCurrent()
{
return arraylist[Cursor];
}
public bool MoveNext()
{
Cursor+=1;
}
}
the same will be done for any other data structure used for storage like array,list etc.
hope this article helps you.
happy coding !!!!
Wednesday, August 15, 2007
Test driven development in dot net using NUnit - part1
I am back with another post today.
we will be discussing about Test Driven Development (TDD).
well the first question is What is TDD?
TDD is the process of developing a software so that the unit testing of the code can be done using some tools (like NUnit or JUnit).
so if use TDD do we have to test in the whole software delivered to the customer ?
YES, we will have to test the whole component after the software is developed.This test will be done to assure that the software is working as per expectations.
but what we must understand is that a software is as good as its individual components.If one of the components of a software is not working fine,then the whole system fails.
a set of classes constitute a component. class will have a set of functions. so we write classes and functions and then we use TDD to test these functions. This assures us that the minute parts of the system are working fine.
but we will have to follow some Object Oriented guidelines for using TDD:
1) we should eliminate the duplication of code. i mean to say that a function should not be repeated elsewhere in the particular component. This assures us of optimal reuse.So we should make sure that classes do not have common methods.
2) if an operation is being performed in several different places, then it is better to create a function for this operation and call that function.
Reason : let us consider a scenario where we are doing a string comparison in several different places.example
str.ToUpper()==str2.ToUpper().
now at a later point of time i realize that i have to change this, then i will have to make the changes at several different places where i am doing this operation.
3) Every operation or action being performed should be broken down in to a single individual function so that it will be easy to test that particular functionality.
example :
factorial of 5 = 5*4*3*2*1 = 120
we do code for this as
public int factorial(int num)
{
int result =1;
while (num>1)
{
result = result * num;
num= num-1;
}
return result;
}
but now if the factorial function for 5 returns 60 instead of 120,what may be the reason?
we will have to debug and find out.
if there any other way?can we just see the test results and ascertain where it fails?
can we make this more testable?
yes, we can create two new functions -for multiply and then subtract.
public int factorial(int num)
{
int result =1;
while (num>1)
{
result = multiply(result,num);
num= subtract(num,1);
}
}
public int Multiply(int num1,int num2)
{
return num1* num2;
}
public int Subtract(int num1,int num2)
{
return num1-num2;
}
so now it becomes easy for us to test the factorial functionality. the advantage being if the factorial function is not giving the expected results, then we can find out where it fails by the tests for multiply and subtract functions.
in my next post, we can discuss how to use NUnit for testing.
Sunday, August 5, 2007
Adapter Pattern : adapt your interfaces
hi,
oen of the problems which i faced while developing some component was with arraylist. This arraylist is present in System.Collections namespace. teh problem which i faced was that, i had created an arraylist to hold a particular interface (say for my game , it would be ICar interface). now i add objects of type car here into the arraylist, and while retrieving objects from the arraylist, i type cats it to ICar. it works fine. but a new requirement arises and we have to keep track of a new interface IPlane in the arraylist. so, while retrieving , i will have to typecast the object to ICar and if an exception is thrown, catch it and typecast the same object to IPlane. this is not proper code, why? because tomorrow, if i want to add a new interface IShip to Arraylist, ihaev to catch another exception and then typecast it to IShip? exactly, then my code will be filled with only try catch block in a nested format. But wher did i go wrong in the design? i had a n interface, i did the best possible design. yes, until here, i have done the best possible design.but where i went wrong was directly adding the object which implement IPlane interface to the arraylist. This caused confusion between ICar and IPlane in the arraylist while retrieving. yes i do have a solution for this problem. we have to wrap the Plane Object in someother class. Also this wrapper for IPlane whould conform to ICar interface...confusing? in simple terms, we introduce a new class which composes of IPlane and implements ICar. This is the Adapter Class. this Adapts IPlane to conform to ICar.
See the code below :
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern
{
public interface ICar
{
//some properties here
}
class Audi : ICar
{
public Audi()
{
}
//implemnt the interface here
}
class Benz : ICar
{
public Benz()
{
}
//implemnt the interface here
}
public class CarFactory
{
public CarFactory()
{
}
}
I have an arraylist wher in i add CarObjects,
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Now i introduce a new mode of tranport- a plane (it flies instead of moving on land).
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
transportVehicles.Add((IPlane)new Plane());
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Then iwll get an exception, coz the second object in the arraylist is of type IPlane and it cannot be typecasted to ICar.
So now i introduce another class called the Adapter which Adapts the Iplane interface to ICar interface
public class PlaneAdapter : ICar
{
IPlane plane;
public PlaneAdapter(IPlane planeobject)
{
plane = planeobject;
}
public void Move()
{
plane.Fly();
}
}
And then change the method of invoking to
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
transportVehicles.Add((ICar)new PlaneAdapter((IPlane)new Plane())); // notice the change here
//Plane adapter implements ICar, so we can type cats PlaneAdapter to ICar
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Now there will be no exception and also teh output will be
car is moving
The plane is flying
All I did was to introduce another class which implemented ICar and composed IPlane. This worked like magic for me!! hope this will help you too.
Happy Coding!!!
Factory - manufacture objects
hi,
Another post, another pattern !!!!
Scenario :
My good old car racing game. But now the car models have been decided. now i would like to use an Audi and a Benz. So we have a ICar interface which is implemented by two car classes - Audi and Benz.but when i haev to create an instance of the Car class, i will have to pass the car model as parameter. the code will be somewhat like :
if(CarModel == ECarModel.AUDI) // ECarModel is an enum
{
return new Audi();
}
else if(CarModel ==ECarModel.BENZ)
{
return new Benz();
}
This code will be used whenever i want to create an instance of a car. i would create a instance of car for many scenarios like : car upgrade, new car bought, new car won as an award etc. so i will have to replicate this code snippet everywhere. now i want to enhance my game i want to include a few more models like Diablo. Does it mean i have to change the code snippet where ever it is present? yes, of course,i will have to do it. hey , what if i make changes to the existing design itself so that i can accomodate any future enhancements? yes, i need to do it. HOW? i will introduce a new class which deals with creating instances for the cars. this class will be called as CarFactory. it deals only with creating instances of Car class- that is the only purpose of the class. so next time any new car is introduced, i need to change this factory class.
Code is as given below :
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern
{
public interface ICar
{
//some methods for the car like move(),break(),spo(),increaseGear(),DecreaseGear() here
}
class Audi : ICar
{
public Audi()
{
}
//implemnt the interface here
}
class Benz : ICar
{
public Benz()
{
}
//implemnt the interface here
}
public class CarFactory
{
public CarFactory()
{
}
public ICar createCar(string Cartype) // instead of a string i can also pass an enum here
{
if (Cartype == "Audi")
{
return new Audi();
}
if (Cartype == "benz")
{
return new Benz();
}
else
return null;
}
}
}
this is the factory pattern!!! the responsibility of creating the class is handed over to the factory for that class.
Happy coding !!!
State pattern : states as objects
Hi,
i am back with another post.This time it is a new pattern - State Pattern. Consider this scenario : i want to develop a car racing Game. so i have the Car class with ICar interface. i have to increase or decrease the gear in the car so, i have the same methods in the interface. i have an enum for all the gears. as of now, the car has only two gears. so the enum will have two entries - neutral and first gear. the car class implements the IncreaseGear() function
void ICar.IncreaseGear()
{
if (State == GearState.Neutral)
{
State = GearState.FirstGear;
}
}
this is the code for the whole game as of now:
using System;
using System.Collections.Generic;
using System.Text;
namespace StatePattern
{
enum GearState
{
Neutral = 0,
FirstGear =1
}
interface ICar
{
void IncreaseGear();
void DecreaseGear();
}
class Car : ICar
{
GearState State = GearState.Neutral;
public Car()
{
State = GearState.Neutral;
}
#region ICar Members
void ICar.IncreaseGear()
{
if (State == GearState.Neutral)
{
State = GearState.FirstGear;
}
if (State == GearState.FirstGear)
{
//Do nothing
}
}
//this will be implemented later on
void ICar.DecreaseGear()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
one - in the enum
two - in the IncreaseGear() function, i will have to put one more if condition
three - in the DecreaseGear() function, i will have to put one more if condition.
thats is ok as i feel that the changes are minimal.
A few days later, i want my car to upgrade and then i introduce a third gear.
again will have to make changes everywhere.
somehow i feel very uncomfortable here. then i think whether there is another way wherein i can make it more flexible and open to enhancement. yes of course, there is a way.
we can treat every individual gear as a state (nothing but another class) and then let the state itself handle what it wants to do.
so we will have a GearState interface. all gears (neutral, first , second etc) implement this interface. The car class composes of the GearState as a member. Car class implements ICar in such a way that it calls the GearState's Increase and Decrease function for the ICar's methods.
Code is as given below :
using System;
using System.Collections.Generic;
using System.Text;
namespace StatePattern
{
interface GearState
{
GearState Increase();
GearState Decrease();
}
public class FirstGear : GearState
{
public FirstGear()
{
}
#region GearState Members
public GearState Increase()
{
Console.WriteLine("first Gear");
return this;
}
public GearState Decrease()
{
Console.WriteLine("reducing the gear state to neutral");
return new Neutral();
}
#endregion
}
public class Neutral : GearState
{
public Neutral()
{
}
#region GearState Members
public GearState Increase()
{
Console.WriteLine("Increasing to First Gear");
return new FirstGear();
}
public GearState Decrease()
{
Console.WriteLine("Cannot decrease Further,already in neutral");
return this;
}
#endregion
}
interface ICar
{
void IncreaseGear();
void DecreaseGear();
}
class Car : ICar
{
GearState State;
public Car()
{
State = new Neutral();
}
#region ICar Members
public void IncreaseGear()
{
State.Increase();
}
public void DecreaseGear()
{
State.Decrease();
}
#endregion
}
}
now if i want to introduce a new gear, i just implement the GearState interface and then implement the functions for increase and decrease. and in the FirstGear class, retru nan instance of SecondGear in the increase Function.
notice how flexible and simple this is.
Happy coding !!!!!
regards,
nandan
Monday, July 30, 2007
Observer pattern : broadcast the message
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 !!!