定义一个纸张的接口
package interfer;
public interface Paper {
public String getSize();
}
定义一个打印机的接口
package interfer;
public interface InBox {
public String getColor () ;
}
A4纸的实现类
package impl;
import interfer.Paper;
public class A4Paper implements Paper {
public String getSize() {
return "A4纸";
}
}
B5纸的实现类
package impl;
import interfer.Paper;
public class B5Paper implements Paper {
public String getSize() {
return "B5纸";
}
}
黑色墨盒的实现类
package impl;
import interfer.InBox;
public class BlackBox implements InBox {
public String getColor() {
return "黑色墨盒";
}
}
彩色墨盒的实现类
package impl;
import interfer.InBox;
public class ColorBox implements InBox {
public String getColor() {
return "彩色墨盒";
}
}
打印机类
package Test;
import interfer.InBox;
import interfer.Paper;
//打印机类,打印机里的是属性是接口
public class PrinterMac {
private InBox box; //这是接口
private Paper paper;//这是接口
public void priter() {
System.out.println("使用" + box.getColor() + ",打印" + paper.getSize()
+ "大小的纸张内容!");
}
//get、set方法
public void setBox(InBox box) {
this.box = box;
}
public void setPaper(Paper paper) {
this.paper = paper;
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!--定义所有墨盒组件 --><!--这里放的是纸张和墨盒的实现类而不是接口 -->
<bean id="black" class="impl.BlackBox"></bean>
<bean id="color" class="impl.ColorBox"></bean>
<!--定义所有纸张 --><!--这个实现类是有返回值的,返回什么纸张 -->
<bean id="A4" class="impl.A4Paper"></bean>
<bean id="B5" class="impl.B5Paper"></bean>
<!--装配打印机 (A4纸,黑色的墨盒) --><!--这里的实现类是有返回值的,返回是颜色的墨盒 -->
<bean id="p1" class="Test.PrinterMac">
<property name="box" ref="black"></property><!--这里的name是本类里的属性 ,是set方法名。ref是上面实现类的id名-->
<property name="paper" ref="A4"></property>
</bean>
<!--装配打印机 (B5纸,彩色的墨盒) -->
<bean id="p2" class="Test.PrinterMac">
<property name="box" ref="color"></property>
<property name="paper" ref="B5"></property>
</bean>
</beans>
测试类
package Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) { //配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 装配好的第一台打印机
PrinterMac pm1 = (PrinterMac) ac.getBean("p1");
pm1.priter();
// 装配好的第二台打印机
PrinterMac pm2 = (PrinterMac) ac.getBean("p2");
pm2.priter();
}
}