Search code examples
oopinheritancedesign-patternsbridge

In the Bridge design pattern, can a specialized function be added to a single implementation?


In my class diagram below, I tried to use the Bridge design pattern to implement a simple document creator application. The concrete "DocMakers" are in charge of doing the document layout, but they each accept a "IFileFormat" to generate each document to different format

My problem is that I want to be able to modify a document in a special way if it is a PDF

I want this special PDF function to happen at the end of the document creation whether it is a DocMakerLayoutA or DocMakerLayoutB, but since everything is ruled by the interfaces, I can't seem to find a place for it.

If I added the function "DoSomethingSpecialForPDF" to "IDocMaker", it would work, but for the "FileFormarBMP" class, I would have to make it perform no action. That just seems like bad design.

Have I designed this thing wrong from the start, or is there a way to do this with this structure?

Sample class diagram using Bridge design pattern


Solution

  • Bridge Pattern is appropriate when you need to decouple abstraction and implementation. in your case you need to look at file creation in abstract, so a Layout must not be aware of concrete File properties. so when you use bridge pattern, you can not assume special behaviour for a special implementation.

    In your case, you can assume that any File have a function after document creation, so you can add a doAfter() method to IFileFormat and implement it in two concrete PDF and BMP. in case of PDF, in doAfter(), you call doSomthingSpecialForPdf and in case of BMP you do nothing.

    You may say it seem like bad design :), but actually you have now Bridge Pattern's benefits (independent variation of two side) If you think to this at first.

    but one key point here is the answer to this question : who is responsible for the special PDF function? or who's the special function really related to? File or Layout?