Home > database >  Correct way to add a print functionality to a java class [closed]
Correct way to add a print functionality to a java class [closed]

Time:09-18

Lets say I have class Report and I want to add a functionality printReport(...) and shouldBePrinted(...). Printing it requires GeneralPrinter and LanguageTranslator which are given from outside. Furthermore, I should add members to make the shouldBePrintable method more optimized.

The way I see it there are three ways of doing it:

  1. The simplest is to just add the members and functions to the Report class.
  2. Create PrintableReport which extends Report and adds those members and functions.
  3. Use the decorator pattern to add the needed functionality. (Not sure about that one. Please correct me if this is not the correct way to use a decorator.)

Am I missing some and which is the correct method to do it?

CodePudding user response:

Consider: Separation of concerns

At a HIGH level...

While it's not clear exactly what role Report fills, one might surmise it represents information organized in some fashion.

Rendering is a separate concern. Often you'll want multiple ways to render: Generate PDF, HTML, XML, and/or print (postscript, other...).

So, perhaps you have multiple classes to work with Report, GeneralPrinter, ReportPrinter, ...

CodePudding user response:

You could create an internal printer MyPrinter that would extend(inherit or composite) the GeneralPrinter.

Most of the time the simplest solution is the best (KISS principle).

  • Related