使用DI依赖注入实现简单电脑组装
#结构图
##建项目 导入包
##建实体包Computer 创建cpu接口
package com.Computer;
public interface ICpu {
public void process();
}
##建两个实现cpu接口类(InterCpu,AMDCpu)
public class InterCpu implements ICpu {
@Override
public void process() {
System.out.println("使用InterCpu");
}
}
public class AMDCpu implements ICpu {
@Override
public void process() {
System.out.println("使用AMDCPU");
}
}
##建IDisplay显示器接口
package com.Computer;
public interface IDisplay {
public void display();
}
##两个实现接口类(LGDisplay,SXDisplay)
public class LGDisplay implements IDisplay {
@Override
public void display() {
System.out.println("使用LG显示器工作");
}
}
public class SXDisplay implements IDisplay {
@Override
public void display() {
System.out.println("使用三星显示器工作");
}
}
##建实体类Computer 使用Setters方法
public class Computer {
private String name;
private ICpu icpu;
private IDisplay idisplay;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ICpu getIcpu() {
return icpu;
}
public void setIcpu(ICpu icpu) {
this.icpu = icpu;
}
public IDisplay getIdisplay() {
return idisplay;
}
public void setIdisplay(IDisplay idisplay) {
this.idisplay = idisplay;
}
public void work1() {
System.out.println(this.name + "电脑在工作");
this.idisplay.display();
this.icpu.process();
}
public void work2() {
System.out.println(this.name + "电脑在工作");
this.idisplay.display();
this.icpu.process();
}
}
##建config源文件包并配置xml文件(spring-config-computer.xml)
<?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.xsd">
<bean id="ac" class="com.Computer.AMDCpu">
</bean>
<bean id="ic" class="com.Computer.InterCpu">
</bean>
<bean id="ld" class="com.Computer.LGDisplay">
</bean>
<bean id="sd" class="com.Computer.SXDisplay">
</bean>
<bean id="c1" class="com.Computer.Computer">
<property name="name" value="联想"></property>
<property name="icpu" ref="ac"></property>
<property name="idisplay" ref="ld"></property>
</bean>
<bean id="c2" class="com.Computer.Computer">
<property name="name" value="惠普"></property>
<property name="icpu" ref="ic"></property>
<property name="idisplay" ref="sd"></property>
</bean>
</beans>
## 测试
public class CTest {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("spring-config-computer.xml");
Computer c1=ac.getBean("c1",Computer.class);
c1.work1();
Computer c2=ac.getBean("c2",Computer.class);
c2.work2();
}
}
##运行结果