直接上代码
import java.util.Arrays;
class Processor {
public String name() {
return getClass().getSimpleName();
}
Object process(Object input) {return input;}
}
class Upcase extends Processor {
String process(Object input) {
return ((String)input).toUpperCase();
}
}
class Downcase extends Processor {
String process(Object input) {
return ((String)input).toLowerCase();
}
}
class Splitter extends Processor {
String process(Object input) {
return Arrays.toString(((String)input).split(" "));
}
}
public class Apply {
public static void process(Processor p, Object s) {
System.out.println("Using Processor ----> " + p.name());
System.out.println(p.process(s));
}
public static String s = "Disagreement with beliefs is by definition incorrect";
//恒定不变的部分
public static void main(String[] args) {
process(new Upcase(), s);
process(new Downcase(), s);
process(new Splitter(), s);
}
}
输出
Using Processor ----> Upcase
DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT(全部大写)
Using Processor ----> Downcase
disagreement with beliefs is by definition incorrect(全部小写)
Using Processor ----> Splitter
[Disagreement, with, beliefs, is, by, definition, incorrect](按单词分开为数组)
Apply.process(Processor p,Object s) 方法 有两个参数,第一个参数是可变部分,第二个参数是固定不变部分。
传入方法的第一个参数,可以变化,从而带来不同的行为(不同的处理方式)。
第二个参数
public static String s = "Disagreement with beliefs is by definition incorrect";
//恒定不变