jeudi 31 octobre 2019

Template method pattern in java

I have assignment in java ,I need help please. I tried to solve it but I have some problem that can't understand them.

Assignment is: In this exercise, use the Template method pattern to define an abstract class Filter with a public method filter (the template method) that calls the method accept (the hook method) that can be implemented in different ways in the different concrete classes. Write a test program by extending the class Filter and defining accept so that only strings of at most three characters are accepted.

enter code here

/*================= Abstract filter class ===================*/

public abstract class Filter<T> {
public abstract T[] filter(T[] list);
public abstract boolean accept(T val);
}

  /*=====================Filter Test class====================*/
   public class FilterTest<T> extends Filter<T>{

   private int capacity = 0;
   public FilterTest(int cap)
   {
   this.capacity = cap;
   }

 @Override
 public T[] filter(T[] list1) {

 @SuppressWarnings("unchecked")
 T[] finalList = (T[])    
     Array.newInstance
 (list1.getClass().getComponentType(), capacity);
  int counter = 0;
 for(T t : list1){
  if(accept(t)){
  finalList[counter] = t;
 counter++;
  }
 }
 return finalList;
}

public void printArray(T[] list2){
for(int i = 0; i < list2.length; i++){
  if(list2[i] != null){
     System.out.print(list2[i] + " ");
     }
 }
     System.out.println();
     }

@Override
public boolean accept(T val) {
if(String.valueOf(val).length() > 0 && String.valueOf(val)
.length()<= 3)
  return true;
  else
  return false;
  }


public static void main(String[]args){
FilterTest<String> filterTest = new FilterTest<String>(8);
String[] lists = {"Hi","here", "is", "the", "AOOP",
"course", "at", "University"};

System.out.print("My original list is: ");
filterTest.printArray(lists);

System.out.print(" The filtered list is: ");
String[] filteredList = filterTest.filter(lists);
filterTest.printArray(filteredList);
 }
 }

Here is comment from my teacher: "not correct, only the accept method should be abstract in the Filter class, the filter method should be already implemented in the Filter class and not be abstract all implementation will be the same, only the accept method changes for different filters)".

I don't understand what should I do now, how the code will be correct. help please, Thanks

Aucun commentaire:

Enregistrer un commentaire