目录结构 files structure
新建一接口
new Interface
Usb.java
1 package test; 2 3 public interface Usb { 4 5 public void read(); 6 public void write(); 7 8 }
Udisk.java
1 package test; 2 3 public class Udisk implements Usb { 4 5 @Override 6 public void read() { 7 // TODO Auto-generated method stub 8 System.out.println("Udisk read();"); 9 10 } 11 12 @Override 13 public void write() { 14 // TODO Auto-generated method stub 15 System.out.println("Udisk write();"); 16 17 } 18 19 }
MoveDisk.java
1 package test; 2 3 public class Movedisk implements Usb { 4 5 @Override 6 public void read() { 7 // TODO Auto-generated method stub 8 System.out.println("Movedisk read();"); 9 10 } 11 12 @Override 13 public void write() { 14 // TODO Auto-generated method stub 15 System.out.println("Movedisk write();"); 16 17 } 18 19 }
Computer.java
1 package test; 2 3 public class Computer { 4 5 6 private Usb usb; 7 8 public Usb getUsb() { 9 return usb; 10 } 11 12 public void setUsb(Usb usb) { 13 this.usb = usb; 14 } 15 16 public void test(){ 17 18 usb.read(); 19 usb.write(); 20 21 } 22 23 }
beans.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE beans PUBLIC "" "http://www.springframework.org/dtd/spring-beans.dtd" > 3 <beans> 4 5 <bean id="helloSpring" class="test.HelloSpring"> 6 <property name="name" value="杨力权"></property> 7 </bean> 8 9 <bean id="uDisk" class="test.Udisk"></bean> 10 <bean id="moveDisk" class="test.Movedisk"></bean> 11 12 <bean id="computer" class="test.Computer"> 13 <property name="usb" ref="uDisk"></property> 14 </bean> 15 16 </beans>
Tester.java
1 package test; 2 3 import org.springframework.beans.factory.BeanFactory; 4 import org.springframework.beans.factory.xml.XmlBeanFactory; 5 import org.springframework.core.io.ClassPathResource; 6 import org.springframework.core.io.Resource; 7 8 @SuppressWarnings("deprecation") 9 public class Tester { 10 11 public static void main( String[] args){ 12 13 Resource r = new ClassPathResource("beans.xml"); 14 BeanFactory factory = new XmlBeanFactory(r); 15 16 Computer computer = (Computer) factory.getBean("computer"); 17 computer.test(); 18 19 } 20 21 }
result
把程序的流转控制,以配置文件的方式来设置接口,这就是我目前理解的 “控制反转”。