标签:
场景:现在有个磁盘输出的业务,客户端需要通过2个业务对象进行输出。 一个是通过Floppy(软盘),另一个是通过USB接口。
1、 定义一个接口
例如:
package spring.basic.BusinessFactory;
public interface IDeviceWriter {
public void saveToDevice();
}
2、 定义实现接口的类(重写接口方法)
例如:(此处定义了两个实现接口的类)
类FloppyWriter:
package spring.basic.BusinessFactory;
public class FloppyWriter implements IDeviceWriter {
public void saveToDevice() {
System.out.println("储存至软盘…");
}
}
类UsbDiskWriter:
package spring.basic.BusinessFactory;
public class UsbDiskWriter implements IDeviceWriter {
public void saveToDevice() {
System.out.println("储存至移动硬盘…");
}
}
3、 定义业务类(指定该类的功能)
package spring.basic.BusinessFactory;
public class BusinessBean {
private IDeviceWriter writer;
public void setDeviceWriter(IDeviceWriter writer) {
this.writer = writer;
}
public IDeviceWriter getDeviceWriter() {
return writer;
}
public void save() {
if (writer == null) {
throw new RuntimeException("DeviceWriter needed...");
}
writer.saveToDevice();
}
}
4、 定义配置文件(将实现接口的类和业务类写入配置文件中)
例如:
<?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-2.0.xsd">
<bean id="floppy" class="spring.basic.BusinessFactory.FloppyWriter"/>
<bean id="usb" class="spring.basic.BusinessFactory.UsbDiskWriter"/>
<bean id="businessBean"
class="spring.basic.BusinessFactory.BusinessBean">
<property name="deviceWriter">
<ref bean="floppy"/>
</property>
</bean>
</beans>
5、 定义客户端代码
package spring.basic.BusinessFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"businessFactoryConfig.xml");
BusinessBean business = (BusinessBean) context.getBean("businessBean");
business.save();
}
}
标签:
原文地址:http://www.cnblogs.com/DoveZoe/p/5418784.html