-3

I have four similar classes which only differ in type of created object inside them.
Like this

public class ImportingWarehouseP //ImportWarehouseW, ImportDictionary, ImportSupplier
{
    private ArrayList<WarehouseP> list = new ArrayList<WarehouseP>();

    public void importWarehouseP(File fileName) throws FileNotFoundException
    {
        FileReader in = new FileReader(fileName);
        Scanner src = new Scanner(in);
        src.useDelimiter("\n");
        src.next();
        for (int g = 0; src.hasNext(); g++) 
        {           
            String record = src.next();
            String [] asdf = record.trim().split(";|:");
            WarehouseP ob = new WarehouseP (asdf);  //here is the difference instead WarehouseP  can be WarehouseW, Dictionary, Supplier

            list.add(ob);
        }           

    }
    public ArrayList<WarehouseP> getList()
    {
        return list;
    }
}

Is it possible to create one uniwersal class "Import" and and only in main specify what type of List I wanna get? e.g

public static void main(String[] args){
    File warehousePFile = new File(path);
    ImportWarehouseP ImpWP = new Import<WarehouseP>();
    ImpWP.importWarehouseP(warehousePFile);
    ArrayList<WarehouseP> recordsWP = ImpWP.getList();
}
BackSlash
  • 21,927
  • 22
  • 96
  • 136

1 Answers1

0

You do this using either an abstract class with a method to generate the object, or using the strategy pattern and passing in a factory to generate the object.

First Approach

new Import<WarehouseP>() {
   protected List<WarehouseP> buildList() {
       return new ArrayList<WarehouseP>();
   }
}

Where

abstract class Import<T> {
     protected abstract List<T> buildList();
}

Second Approach

new Import<WarehouseP>(new ListBuilder<WarehouseP>() {
   public List<WarehouseP> buildList() {
       return new ArrayList<WarehouseP>();
   }
});

Where

interface ListBuilder<T> {
     public abstract List<T> buildList();
}

The first approach is simpler, the second tends to be cleaner.

Tim B
  • 40,716
  • 16
  • 83
  • 128