hi,
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 !!!