vendredi 24 avril 2020

Designing a filter interface with a template method pattern

I have done a filter interface that filters out all the strings that have more than 3 letters without any particular pattern. How do i now define a abstract class Filter with a public method filter that calls the method acept that can be implemented in different ways? All of this using Template method pattern?


public class WordFilter extends Filter{

    public boolean accept(String obj){

        return(((String) obj).length() <= 3);
    }

}

import java.util.Arrays;

public class RunHere {

public static void main(String[] args) {

    String[] theArray = { "oig3", "jt3jjt3", "wee", "02ri", "Adam", "lel", "32", "k" };

    System.out.println(Arrays.toString(theArray));

    WordFilter filt = new WordFilter();

    String[] resultat = filter(theArray, filt);

    System.out.println(Arrays.toString(resultat));

}

public static String[] filter(String[] a, Filter f){

    String x;
    int count = 0;
    int pos = 0;

    for (int i = 0; i < a.length; i++) {
        x = a[i];
        if (x.length() < 4) {
            count++;
        }

    }

    System.out.println("Count is :" + count);

    String[] filtered = new String[count];

    for (int i = 0; i < a.length; i++) {

        if (f.accept(a[i])) {
            filtered[pos] = a[i];
            pos++;
        }

    }

    return filtered;

}

}

public abstract class Filter {

    abstract boolean accept(String x);


    }


Aucun commentaire:

Enregistrer un commentaire