Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern can i use in JAVA for this requirement

I have 3 different types of files in a folder. Every file has same data which is saved into Employee Table.

File Types:

  1. XML
  2. Excel
  3. .txt

I have written 3 separate classes which have two methods, take a filePath as String parameter and return an EmployeeVO Object or a List<EmployeeVO>.

I want to remove these if else.

List<EmployeeVO>  list ;
 if(fileName.endsWith(".xml")){
    list =   XmlReader();
 }else if(fileName.endsWith(".EXCEL")){
    list =     ExcelReader();
 }else if(fileName.endsWith(".TXT")){
    list =     TxtReader();
 }
like image 816
HakunaMatata Avatar asked Dec 10 '25 13:12

HakunaMatata


1 Answers

I think that you can use the Command pattern here. It can be used to replace cumbersome switch / if blocks which tend to grow indefinitely as you add new options.

Another option may be the Factory pattern. You include your if / switch in a Factory which takes care of the ugliness and hides the abundance of ifs.

Of course you can combine both. It only depends on your preference and the context where you are using it.

And by the way: don't use patterns just because they are fancy use them where you need them.

like image 66
Adam Arold Avatar answered Dec 12 '25 03:12

Adam Arold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!