In OOP we use polymophism so an abstraction can have multiple implementations. Lets look at the following example -:
public interface Train
{
void move();
}
public class MonoRail:Train
{
public override void move()
{
//use one track;
}
}
public class ElectricMonoRail:MonoRail
{
public override void move()
{
//use electircelectric engine on one track.
}
}
public class DieselMonoRail: MonoRail
{
public override void move()
{
//use diesel engine on one track.
}
}
public class Rail:Train
{
public override void move()
{
//use two tracks;
}
}
public class ElectricRail:Rail
{
public override void move()
{
//use electircelectric engine on two tracks.
}
}
public class DieselRail: Rail
{
public override void move()
{
//use diesel engine on two tracks.
}
}
The above code is not maintainable and lack of reusability (assuming we could reuse the acclerationacceleration machanism for the same track platform). Following code apply bridge pattern and seperateseparate the two different abstractions, train transport and acceleration.
public interface Train
{
void move(Accelerable engine);
}
public interface Accelerable
{
public void acclerateaccelerate();
}
public class MonoRail:Train
{
public override void move(Accelerable engine)
{
//use one track;
engine.accelerate();engine; //engine is pluggable (runtime dynamic)
}
}
public class Rail:Train
{
public override void move(Accelerable engine)
{
//use two tracks;
engine.accelerate(); //engine is pluggable (runtime dynamic)
}
}
public class ElectricEngine:Accelerable{//implementation*implementation code for acceleableaccelerable*/}
public class DieselEngine:Accelerable{//implementation*implementation code for acceleableaccelerable*/}