/** * 书本:《Thinking In Java》 * 功能:完全解耦,策略设计模式 * 这里apply.process()方法可以接受任何类型的processor,并将其应用到一个Object对象上,然后打印结果 * 文件:Apply.java * 时间:2015年4月2日16:50:55 * 作者:cutter_point */ package Lesson9Interfaces.classprocessor; import static net.mindview.util.Print.*; import java.util.Arrays; class Processor { public String name() { return this.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) { print("Using Processor" + p.name()); print(p.process(s)); } public static String s = "I like China, I`m Chinese, I can!"; public static void main(String [] args) { Processor p = new Processor(); System.out.println(p.name()); process(new Upcase(), s); process(new Downcase(), s); process(new Splitter(), s); } }
结果:
Processor
Using ProcessorUpcase obj1
I LIKE CHINA, I`M CHINESE, I CAN! obj1
Using ProcessorDowncase obj1
i like china, i`m chinese, i can! obj1
Using ProcessorSplitter obj1
[I, like, China,, I`m, Chinese,, I, can!] obj1
时间: 2024-11-15 08:18:38