java - fully decoupled

Keywords: Java

Fully decoupled: reduce the limitation of code. The same code can be used in more programs

 1 package interfaces.interfaceprocessor;
 2 import static net.mindview.util.Print.print;
 3 
 4 interface Processor {
 5     String name();
 6     Object process(Object input);
 7 }
 8 public class Apply{
 9     public static void process(Processor p, Object s) {
10         print("Using Processor "+ p.name());
11         print(p.process(s));
12     }
13 }

The above method code Apply.process () prints out the name of the process and the process of the process. This code can be used by anyone who meets this requirement




 1 package interfaces.interfaceprocessor;
 2 import static net.mindview.util.Print.*;
 3 
 4 public abstract class StringProcessor implements Processor {
 5     public String name() {
 6         return getClass().getSimpleName();
 7     }
 8     public abstract String process(Object input);
 9     public static String s = "if she weights the same as duck";
10     public static void main(String[] args) {
11         Apply.process(new Upcase(), s);
12     }
13 }
14 class Upcase extends StringProcessor{
15     public String process(Object input) {
16         return ((String)input).toUpperCase();
17     }
18 }

 


 

 

When using the Apply.process() method, an adapter method is needed. In this case, StringProcessor is a string adapter, which is the implementation of the interface Processor

Because the parameter received by the Apply.process() method is of Proessor type, it is necessary to implement a Processor interface. We call it an adapter, which is also the implementation of the interface Processor, so the type of the adapter is also Processor

In this way, you can pass the contents of the adapter to the Apply.process() method (apply. Process (New upacase())

package interfaces.interfaceprocessor;

class ChacaterPairSwapper{
    public String swap(String s) {
        StringBuilder sb = new StringBuilder(s);
        for(int i=0; i<sb.length()-1; i=i+2) {
            char c1 = sb.charAt(i);
            char c2 = sb.charAt(i+1);
            sb.setCharAt(i, c2);
            sb.setCharAt(i+1,c1);
        }
        return sb.toString();
    }
}
class SwapAdapator implements Processor{
    ChacaterPairSwapper cps = new ChacaterPairSwapper();
    public String name() {
        return ChacaterPairSwapper.class.getSimpleName();
    }
    public Object process(Object input) {
        return cps.swap((String)input);
    }
}
public class E11_Swap {
    public static void main(String[] args) {
        Apply.process(new SwapAdapator(), "1234");
    }
}

This example also uses the Apply.process() method. First, write a method to exchange a pair of characters, and then write an adapter of this method to adapt it to the Apply.process() method

 

This is complete decoupling, which enables more code to use the same method through adapters

Posted by houssam_ballout on Fri, 22 Nov 2019 06:54:18 -0800