策略模式(Strategy):
定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。
在Guava的Splitter类中便用到了这种模式——
字符串的分割方式:
1、根据单个字符分割
public static Splitter on(char separator) {
return on(CharMatcher.is(separator));
}
实际调用的也是下面的第二种方式。
示例:Splitter.on(',').split("foo,,bar") ;
结果:["foo", "", "bar"]
2、根据CharMatcher分割
static Splitter on(final CharMatcher separatorMatcher)
返回的Splitter为:
return new Splitter(new
Strategy() {
@Override public SplittingIterator
iterator(
Splitter splitter, final CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override int separatorStart(int start) {
return separatorMatcher.indexIn(toSplit, start);
}
@Override int separatorEnd(int separatorPosition) {
return separatorPosition + 1;
}
};
}
});
|
示例:Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux");
结果:["foo", "", "bar", "quux"]
3、根据字符串分割
static Splitter on(final String separator)
返回的Splitter为:
return new Splitter(new
Strategy() {
@Override public SplittingIterator
iterator(
Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
int delimeterLength = separator.length();
positions:
for (int p = start, last = toSplit.length() - delimeterLength;
p <= last; p++) {
for (int i = 0; i < delimeterLength; i++) {
if (toSplit.charAt(i + p) != separator.charAt(i)) {
continue positions;
}
}
return p;
}
return -1;
}
@Override public int separatorEnd(int separatorPosition) {
return separatorPosition + separator.length();
}
};
}
});
|
示例:Splitter.on(", ").split("foo, bar,baz")
结果: ["foo", "bar,baz"]
4、根据匹配模式分割
static Splitter on(final Pattern separatorPattern)
返回的Splitter为:
return new Splitter(new
Strategy() {
@Override public SplittingIterator
iterator(
final Splitter splitter, CharSequence toSplit) {
final Matcher matcher = separatorPattern.matcher(toSplit);
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
return matcher.find(start) ? matcher.start() : -1;
}
@Override public int separatorEnd(int separatorPosition) {
return matcher.end();
}
};
}
});
|
示例:Splitter.onPattern("\r?\n").split("a\r\nb\nc")
结果: ["a", "b", "c"]