1、策略设计模式
import java.util.Arrays; 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); } } 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(" "))); } }
输出:
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]
分析:对于不同的processor对象(即策略),应用于字符串s会产生不同的行为。
2、适配器设计模式
import java.util.Arrays; public class Adapter { public static void process(Processor p, Object s) { System.out.println("Using processor " + p.name()); System.out.println(p.process(s)); } public static void main(String[] args) { String s = "abcdefg"; process(new ExerAdapter(new Exer()), s); } } interface Processor { String name(); Object process(Object input); } class Exer { String func(String s) { if (s != null && s != "") { char[] split = s.toCharArray(); for (int i = 0; i < split.length - 1; i += 2) { char temp = split[i]; split[i] = split[i + 1]; split[i + 1] = temp; } s = Arrays.toString(split); } return s; } } /** * 适配器转换类 */ class ExerAdapter implements Processor { Exer e; public ExerAdapter(Exer e) { this.e = e; } @Override public String name() { return e.getClass().getSimpleName(); } @Override public Object process(Object input) { return e.func((String) input); } }
输出:
Using processor Exer
[b, a, d, c, f, e, g]
分析:由于Exer与Process接口不一致,所以新增一个ExerAdapter适配器类来对Exer适配,应用于Adapter的process方法。