Using Helper Class To Allow Users To Extend Your Code

In my first article, I explained how you can use a custom listener to allow users to plug into your code. A variation on this is to provide a static Helper class. As before you have an interface with a set of documented methods which are called in your code. Here is an example from our JPedal PDF library.

public interface JPedalHelper {

    //Allow user to replace setFont Method in
    PdfJavaGlyphs public Font
    setFont(PdfJavaGlyphs pdfJavaGlyphs,
    String name, int size);
    //allow user to control Font returned for
    rendering public Font
    getJavaFont(PdfFont pdfFont, int size);

    //allow user to control how color set when rendering
    //(ie to produce grayscale or bw)
    public void setPaint(Graphics2D g2, PdfPaint textFillCol,
int pageNumber, boolean isPrinting);

    //allow user to process images before drawn
    //(ie to convert to bw or grayscale)
    public BufferedImage processImage(BufferedImage image,
int pageNumber,boolean isPrinting);
}

We add a default instance of the Interface in our code with

//allow user to override code
public static JPedalHelper Helper=null;

Because the object Helper is static and public, the user can very easily set it to their own version (which is an instance of our interface) and then access it if is not null in our code.

if (PdfDecoder.Helper != null) {
    BufferedImage newImage = PdfDecoder.Helper.processImage(image,
pageNumber, isPrinting);
    if (newImage != null)
        image = newImage;
}

The methods are static but we are passing in instance values so they can work with multiple instances – there is a slight tradeoff that the static method is not as flexible as a custom interface but much simpler and easier to setup. And it gives users a very easy way to plumb into your application in an easy and controlled way.

If you want to see an example in action, we use it to allow the user to convert PDF files to grayscale.

Comments

Published
Categorized as Java

By Mark Stephens

Mark Stephens runs IDRsolutions, developing the JPedal PDF library in Java, and shares his thoughts on Java, PDF, the Business of Software and Mediaeval History at http://www.jpedal.org/PDFblog .

Leave a comment