java 完全解耦

只要有一个方法操作的是类而非接口,那么你就只能使用这个类及其子类,如果你想要将这个方法应用于不在此继承结构中的某个类,

//像本例这样,创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,被称为策略设计
//策略就是传递进去的参数对象,它包含要执行的代码
//
: interfaces/classprocessor/Apply.java package object; import java.util.*; import static net.mindview.util.Print.*; class Processor { public String name() { return getClass().getSimpleName(); } Object process(Object input) { return input; } } class Upcase extends Processor { String process(Object input) { // Covariant return return ((String)input).toUpperCase(); } } class Downcase extends Processor { String process(Object input) { return ((String)input).toLowerCase(); } } class Splitter extends Processor { String process(Object input) { // The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" "));//split()返回String[]数组 } } 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); } } /* Output: 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] *///:~

那么你就会触霉头,接口可以在很大程度上放宽这种限制,因此,我们可以编写可服用性更好的代码

猜你喜欢

转载自www.cnblogs.com/jiangfeilong/p/10204990.html