In my program I need to create xls or xlsx files and the file type is chosen using an option in a property file.

This is how we can switch xls and xlsx file type using java code

For xls:

Workbook workbook =  new XSSFWorkbook();

For xlsx:

Workbook workbook =  new HSSFWorkbook();

And what I do is, for creating every file I check the variable which contains the file type option in property file.

if(variable which contains the filetype option in properties has xls )
    Workbook workbook =  new XSSFWorkbook();
    Workbook workbook =  new HSSFWorkbook();

I am doing this for ever single files and our processes involves creation of lots of files. There are also conditions for creating filename for these files. Is there any way to fix a specific class(XSSFWorkbook|HSSFWorkbook) at the time of initialization of program and use it throughout the program instead of checking the condition for every file. I thought of singleton pattern but it is use of single object not class.


You want the Factory pattern. You inject a factory that can create Workbooks into the places that need them, and you inject either a XSSFWorkbookFactory or a HSSFWorkbookFactory depending on the property.

For this, you'll probably want to use the Dependency Injection pattern as well, to get the factory to where it's needed.

  • Injection is the way. With Java 8 a Supplier<Workbook> could be injected, which is a sort of easy functional factory. – fabiofili2pi Jul 29 '16 at 8:45
  • Could you please elaborate with example, because i am not that proficient at design pattern. – padippist Jul 29 '16 at 9:03
  • I use java 6, in java 8 we can assign function to a variable, it will also work rite – padippist Jul 29 '16 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.