日期:2014-05-20 浏览次数:20669 次
import java.util.*; 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(" ")); } } class Apply2{ public static void process(Processor p, Object s) { System.out.println("Using Processor " + p.name()); System.out.println(p.process(s)); } } public class Test1{ public static String s ="Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { Apply2.process(new Upcase(), s); Apply2.process(new Downcase(), s); Apply2.process(new Splitter(), s); } }
import java.util.*; 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(" ")); } } class Apply2{ public static void process(Adapter p, Object s) { System.out.println("Using Processor " + p.name()); System.out.println(p.process(s)); } } class Adapter{ Processor mpr; public Adapter(Processor mpr){ this.mpr = mpr; } public String name() { return mpr.name(); } Object process(Object input) { return mpr.process(input); } } public class Test2{ public static String s ="Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { Apply2.process(new Adapter(new Upcase()) , s); //这种通过过滤器般的编程思想在哪些方面有优势?我觉得还是代码1用起来比较方便~ Apply2.process(new Adapter(new Downcase()) , s); Apply2.process(new Adapter(new Splitter()) , s); } }
public class Apply { //只将方法贴出来 public static void process(Processor p, Object s) { print("Using Processor " + p.name()); print(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); } }