java - 使用模板方法模式设计过滤器接口
问题描述
我做了一个过滤器接口,过滤掉所有超过 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);
}
解决方案
模板方法模式在方法中定义了算法的骨架,将一些步骤推迟到子类。但是在您给出的问题中,我看到只有一步(找到大小为 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;
}
推荐阅读
- php - 发送 json 数据时 PHP API 的行为发生变化
- c# - 如何在 SQL Server 中创建一个列来保存不同类型的值
- google-cloud-platform - 如何通过谷歌点击部署在 GKE 中配置的外部 Prometheus 和 Grafana Dashboards 公开
- r - 将测试的输出存储在新变量、向量等中
- groovy - 如何将 Map 的流分组到 Map
>? - javascript - Event.target 仅适用于第一个孩子
- java - 可以将未知对象强制转换为特定接口吗?
- excel - 借助搜索复制特定区域并附加到主 Excel 电子表格
- python - 如何使用python将txt文件转换为json?
- python - ImportError:没有名为 toripchanger 的模块,如何使用正确的 python 版本启动scrapy