首页 > 解决方案 > 使用模板方法模式设计过滤器接口

问题描述

我做了一个过滤器接口,过滤掉所有超过 3 个字母而没有任何特定模式的字符串。我现在如何定义一个带有公共方法过滤器的抽象类过滤器,该过滤器调用可以以不同方式实现的方法 acept?所有这些都使用模板方法模式?

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);
}

标签: javatemplatesdesign-patternsfilter

解决方案


模板方法模式在方法中定义了算法的骨架,将一些步骤推迟到子类。但是在您给出的问题中,我看到只有一步(找到大小为 n 的字符串)。即在找到大小为 n 的字符串之前或之后没有步骤。

如果有东西(多个任务),我会像下面那样做。这将实现模板模式。

public abstract class Filter {
    abstract boolean accept(String x);

    void BeforeStep() {
        // Do something
    }

    void AfterStep() {
        // do something
    }

}


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

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

        **f.BeforeStep();**

        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++;
            }

        }

        f.AfterStep();        

        return filtered;
    }

推荐阅读