/*** Book: Thinking in Java * Features: Adapter design mode * File: processor.java* time: April 2, 2015 20:36:59* Author: cutter_point*/package Lesson9interfaces.interfaceprocessor;public interface Processor {String name (); Object process (object input);}
/*** Book: Thinking in Java * Features: Adapter design mode * File: apply.java* time: April 2, 2015 20:36:59* Author: cutter_point*/package Lesson9interfaces.interfaceprocessor;import Static net.mindview.util.print.*;p Ublic class Apply {public static void Process (Processor p, Object s) {print ("Using Processor" + p.name ());p rint (p.process (s));}}
/*** Book: Thinking in Java * Features: Adapter design mode * File: stringprocessor.java* time: April 2, 2015 20:36:59* Author: cutter_point*/package Lesson9interfaces.interfaceprocessor;import Java.util.arrays;public Abstract class Stringprocessor implements Processor {@Overridepublic String name () {return This.getclass (). Getsimplename ();} @Overridepublic abstract String process (Object input);p ublic static string s = "If She weights the same as a duck, she ' s M Ade of wood ";p ublic static void Main (String [] args) {apply.process (New Upcase (), s); Apply.process (New Downcase (), s); Apply.process (New Splitter (), s);}} Class Upcase extends Stringprocessor{public String process (Object input) {return (String) input). toUpperCase ();}} Class Downcase extends Stringprocessor{public String process (Object input) {return (String) input). toLowerCase ();}} Class Splitter extends Stringprocessor{public String process (Object input) {return arrays.tostring ((String) input). SPL It (""));}}
In the previous article said that the two class coupling is too high, how we decouple in this article, we can do the processor class written interface, so that an abstract class implementation of this interface, then the coupling will become loose, then apply.process () can be reused, Receive an object parameter!!!
Output Result:
Using Processor Upcase obj1
IF She WEIGHTS the same as A DUCK, SHE ' S made of WOOD obj1
Using Processor downcase obj1
If she weights the same as a duck, she ' s made of wood obj1
Using Processor Splitter obj1
[If, she, weights, the, same, as, A, duck,, she ' s, made, of, Wood] obj1
"Thinkinginjava" 12, adapter design mode