控制反转(IoC):Inversion of Control
依赖注入(DI):Dependency Injection
工厂类角色-->BeanFactory
抽象产品角色-->USB
具体产品角色-->UsbMovedDisk
USB接口,,U盘、硬盘设备,,USB工厂
UsbDevice接口:
package com.dao; //抽象产品,USB设备 public interface UsbDevice { //读数据 public void readData(); //写数据 public void writeData(String content); }
U盘和硬盘设备:
package com.entity; import com.dao.UsbDevice; //U盘类 public class UDisk implements UsbDevice{ @Override public void readData() { // TODO Auto-generated method stub System.out.println("U盘读数据中..."); } @Override public void writeData(String content) { // TODO Auto-generated method stub System.out.println("U盘写入数据:"+content); } }
package com.entity; import com.dao.UsbDevice; //移动硬盘 public class MoveDisk implements UsbDevice{ @Override public void readData() { // TODO Auto-generated method stub System.out.println("移动硬盘读数据中...."); } @Override public void writeData(String content) { // TODO Auto-generated method stub System.out.println("移动硬盘写入数据:"+content); } }
工厂类:
package com.factory; import com.dao.UsbDevice; //USB设备的工厂类,负责生产各种USB设备的产品 public class UsbDeviceFactory { public static UsbDevice createUsbDevice(String type){ //利用反射来实现,动态创建USB设备。"com.entity.UDisk" try { Class clazz=Class.forName(type); return (UsbDevice) clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } } }
测试类:
package com.factory; import org.junit.Test; import com.dao.UsbDevice; public class UsbDeviceFactoryTest { @Test public void fun1(){ String type="com.entity.UDisk"; UsbDevice u = UsbDeviceFactory.createUsbDevice(type); u.readData(); u.writeData("茜茜公主"); } }
测试结果:
U盘读数据中... U盘写入数据:茜茜公主
分析:工厂通过反射创建实例
applicationContent.xml文件:
spring通过工厂模式利用反射生成实例(注入)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="mydevice" class="com.entity.MoveDisk"> </bean> </beans>
测试类:
package com.dao; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UsbDeviceTest { @Test public void fun1(){ //获得上下文对象 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); //spring的工厂帮忙注入对象 UsbDevice u = (UsbDevice) ctx.getBean("mydevice");//体现了多态性 //三个特征:1.继承2.方法重写3.父类引用指向子类对象 u.readData(); u.writeData("茜茜公主~~"); } }
测试结果:
移动硬盘读数据中.... 移动硬盘写入数据:茜茜公主~~
原文:https://www.cnblogs.com/xjs1874704478/p/11175073.html