patterncsharpMinor
Class for generating PDF documents
Viewed 0 times
classgeneratingfordocumentspdf
Problem
Following is a chunk of code from my class which generates PDF documents. I am refactoring my code and in the process I have created short methods. But I have to pass 'table i.e PdfPTable' to my methods again and again. How can I avoid this?
PdfPTable orgTable = new PdfPTable(2);
PdfPCell cell = null;
string orgName = dr["OrganizationName"].ToString();
cell = new PdfPCell(new Phrase(orgName, Heading1)) {Colspan = 2, BackgroundColor = BckColor, HorizontalAlignment = Element.ALIGN_CENTER };
orgTable.AddCell(cell);
AddOrganizationProfile(document, dr, orgTable);
OrganizationHeadOffice(document, dr, orgTable);
OrganizationContacts(document, orgTable, orgId);
private void OrganizationHeadOffice(Document document, DataRow dr, PdfPTable table)
{
AddTitle("Office Contact & Information:", table);
// How to avoid passing table variable again and again here.
AddLegend("Address:", table);
AddDataValue(dr["address"].ToString(), table);
AddLegend("Contact Number:", table);
AddDataValue(phone1, table);
}
private void AddTitle(string title, PdfPTable table)
{
table.AddCell(new PdfPCell(new Phrase(title, TableFontCaption)) { Colspan = 2, BackgroundColor = BckColor });
}
private void AddLegend(string legend, PdfPTable table)
{
table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(legend, TableFontCaption) });
}
private void AddDataValue(string dataValue, PdfPTable table)
{
table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(dataValue, TableFont) });
}Solution
This looks like a good candidate for the Builder pattern.
You have a PdfPTableBuilder class, whose sole responsibility is to (of course) build a PdfPTable instance. You initialize it and call various setter methods, and each method returns
The builder itself simply holds all the data it needs to construct the table instance, and pours that into the table in the
You have a PdfPTableBuilder class, whose sole responsibility is to (of course) build a PdfPTable instance. You initialize it and call various setter methods, and each method returns
this, so that you can chain them:PdfPTableBuilder builder = new PdfPTableBuilder();
builder.AddLegend("Address:").AddDataValue(dr["address"].ToString());
// etc.
return builder.build();The builder itself simply holds all the data it needs to construct the table instance, and pours that into the table in the
build method.Code Snippets
PdfPTableBuilder builder = new PdfPTableBuilder();
builder.AddLegend("Address:").AddDataValue(dr["address"].ToString());
// etc.
return builder.build();Context
StackExchange Code Review Q#16225, answer score: 4
Revisions (0)
No revisions yet.