案例:通过不同的纸张和不同类型墨盒的组合,来装配出一台打印机。
架构目录:
步骤一:在ink包下创建Ink接口和其实现类
Ink接口
public interface Ink {
public String getColor();
}
实现类ColorInk
public class ColorInk implements Ink {
public String getColor() {
return "彩色墨盒";
}
}
实现类GrayInk
public class GrayInk implements Ink{
// 打印采用灰色
public String getColor() {
return "灰色墨盒";
}
}
步骤二:在paper包下创建Paper接口及其实现类
Paper接口
public interface Paper {
public String getContent();
}
Paper实现类
public class A4Paper implements Paper {
public String getContent() {
return "一张淡定的A4纸";
}
}
步骤三:在printer包下创建Print类
public class Print {
private Ink ink;
private Paper paper;
public void print(){
System.out.println("用X颜色的墨盒在纸上打印内容");
}
public Ink getInk() {
return ink;
}
public void setInk(Ink ink) {
this.ink = ink;
}
public Paper getPaper() {
return paper;
}
public void setPaper(Paper paper) {
this.paper = paper;
}
}
步骤四:在applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="colorInk" class="cn.happy.ink.ColorInk"/>
<bean id="grayInk" class="cn.happy.ink.GrayInk"/>
<!--对Paper的初始化 -->
<bean id="paper" class="cn.happy.paper.A4Paper"/>
<!-- 对打印机进行配置-->
<bean id="printer"class="cn.happy.printer.Print">
<property name="ink" ref="colorInk"></property>
<property name="paper" ref="paper"></property>
</bean>
</beans>
步骤五:通过Test类测试
public static void main(String[] args) {
ApplicationContextcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
Printprinter = (Print)context.getBean("printer");
Stringcolor=printer.getInk().getColor();
Stringcontent=printer.getPaper().getContent();
System.out.println(color);
System.out.println("===========");
System.out.println(content);
}