Thursday, June 26, 2008

Bridge Design Pattern

The Bridge pattern is useful when a new version of software is brought out that will replace an existing version, but the older version must still run for its existing client base. The client code will not have to change, as it is conforming to a given abstraction, but the client will need to indicate which version it wants to use.(ex. You can have several versions of the .NET Framework loaded on your computer at any time and can select which one to use by externally setting a path to it in the Windows operating system. Setting the path is the bridge between what applications want from the Framework and the actual version they will get).

The design of a bridge and its players is shown in the UML diagram



From this diagram, we can see that the role players for the Bridge pattern are:


Abstraction : The interface that the client sees


Operation : A method that is called by the client


Bridge : An interface defining those parts of the Abstraction that might vary


ImplementationA and ImplementationB :Implementations of the Bridge interface


OperationImp : A method in the Bridge that is called from the Operation in the Abstraction


And this the implementation :


using System;
namespace BridgePattern {
class Abstraction


{
Bridge bridge;
public Abstraction(Bridge implementation) {
bridge =implementation;


}
public string Operation ( )


{
return "Abstraction" +" <<< BRIDGE >>>>"+bridge.OperationIm( );


}
}
interface Bridge


{
string OperationImp( );


}
class ImplementationA :Bridge {
public string OperationImp ( )


{
return"ImplementationA";


}
}
class ImplementationB :Bridge {
public string OperationImp ( )


{
return "ImplementationB";


}
}
class BridgeApp
{
static void Main()
{
Console.WriteLine("Bridge Pattern\n");
Console.WriteLine(new Abstraction(new
ImplementationA()).Operation());
Console.WriteLine(new Abstraction(new
ImplementationB()).Operation());


}
}
}
/* Output
Bridge Pattern
Abstraction <<< BRIDGE >>>> ImplementationA
Abstraction <<< BRIDGE >>>> ImplementationB
*/


Best Regards

No comments: