spring and interfaces

后端 未结 9 806
无人及你
无人及你 2020-12-08 14:45

I read all over the place about how Spring encourages you to use interfaces in your code. I don\'t see it. There is no notion of interface in your spring xml configuration.

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 15:24

    The Dependency Inversion Principle explains this well. In particular, figure 4.

    A. High level modules should not depend on low level modules. Both should depend upon abstractions.

    B. Abstraction should not depend upon details. Details should depend upon abstractions.

    Translating the examples from the link above into java:

    public class Copy {
        private Keyboard keyboard = new Keyboard(); // concrete dependency
        private Printer printer = new Printer();    // concrete dependency
        public void copy() {
            for (int c = keyboard.read(); c != KeyBoard.EOF) {
                printer.print(c);
            }
        }
    }
    

    Now with dependency inversion:

    public class Copy {
         private Reader reader; // any dependency satisfying the reader interface will work
         private Writer writer; // any dependency satisfying the writer interface will work
         public void copy() {
            for (int c = reader.read(); c != Reader.EOF) {
                writer.write(c);
            }
         }
         public Copy(Reader reader, Writer writer) {
             this.reader = reader;
             this.writer = writer;
         }
    }
    

    Now Copy supports more than just copying from a keyboard to a printer.

    It is capable of copying from any Reader to any Writer without requiring any modifications to its code.

    And now with Spring:

    
        
        
    
    
    
    
    

    or perhaps:

    
    
    

提交回复
热议问题