Search code examples
javastrategy-pattern

Strategy pattern to read different file formats


public interface FileReader {

  void readFile();
   void writeFile();
}


 public class XMLReader implements FileReader {

  @Override
   public void readFile() {
    System.out.println("Hellp i am read");

   }

   @Override
   public void writeFile() {
        System.out.println("Hello i am write");
    }


 }

  public class ExcelReader implements FileReader {

  @Override
   public void readFile() {
    System.out.println("Hellp i am read");

   }

   @Override
   public void writeFile() {
        System.out.println("Hello i am write");
    }

}

public class Context {

   FileReader reader ;

   public Context(FileReader reader) {
    super();
    this.reader = reader;
   }

   public void executeRead(){

        reader.readFile();
    }


       }

public class TestStrategy {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println(args[0]);
    String s=args[0];
    String[] a=s.split("\\.");
    if(a[1].equals("csv")){
        new Context(new XMLReader()).executeRead();
    }else{
        new Context(new ExcelReader()).executeRead();
    }
}

}

I have a concern more file format are introduced we will create separate class for them but i have to change the if else code in TestStrategy class to create new object for the file pattern introduced.

Can we remove this if else code .Any suggestions.


Solution

  • You could use a registry that maps a files extension to the implementation.

    public class Registry {
        static Map<String,FileReader> reg = new HashMap<String,FileReader>();
    
        public static void register(String ext, FileReader fr ) {
            reg.put( ext, fr );
        }
    }
    

    and let newly added implementation register themself e.g.

    public class XMLReader implements FileReader {
            static {
                Registry.register( "xml", new XMLReader() );
            }
    ....
    public class ExcelReader implements FileReader {
            static {
                Registry.register( "xls", new ExcelReader() );
            }
    ...
    

    then you could simply lookup the registry for a suitable implementation with no if or switch required.