Printed from www.rmfusion.com A Developer website designed for Developers

Bridge Pattern Code Review

Code Download

Define the Pattern Interface and Handler Objects

Define the IPrinter interface to be used as the "blueprint" for the main Bridge classes.

class PrinterBridge { public interface IPrinter { String printTestPage(); }
public class InkJetPrinter : IPrinter { public string printTestPage() { return("This text has been printed on a Ink Jet Printer"); } } public class LaserPrinter : IPrinter { public string printTestPage() { return("This text has been printed on a Laser Printer"); } } public class DotMatrixPrinter : IPrinter { public string printTestPage() { return("This text has been printed on a Dot Matrix Printer"); } } }

Each Bridge class (object) will contain a different implementation of the required methods.

Define the Portal Object

The PrinterPortal class (object) represents the abstraction component.

class PrinterPortal { private PrinterBridge.IPrinter printer;
public PrinterPortal(PrinterBridge.IPrinter bridge) { printer = bridge; }
public string printOperation() { return printer.printTestPage(); } }

The dependent Bridge class is "injected" into the class constructor.

Use the Bridge Pattern

The Program class creates an instance of the PrinterPortal class "injecting" the different implementations of the Bridge classes.

class Program { static void Main(string[] args) { PrinterPortal portal;
portal = new PrinterPortal(new PrinterBridge.InkJetPrinter()); Console.WriteLine(String.Format("{0}\n", portal.printOperation())); portal = null;
portal = new PrinterPortal(new PrinterBridge.LaserPrinter()); Console.WriteLine(String.Format("{0}\n", portal.printOperation())); portal = null;
portal = new PrinterPortal(new PrinterBridge.DotMatrixPrinter()); Console.WriteLine(String.Format("{0}\n", portal.printOperation())); portal = null;
Console.Read(); } }