依赖注入ioc 组装打印机

£如何开发一个打印机?

£打印机功能的实现依赖于墨盒纸张

£步骤:

1、定义墨盒和纸张的接口标准。

2、使用接口标准开发打印机。

3、组装打印机。

4、运行打印机。

1:

1. 定义组件接口
墨盒接口:Ink
纸张接口:Page
public interface Ink {
public String getColor(int r,int g,int b);
}
public interface Paper {
public static final String newline = "\r\n";
/**
* 输出字符到纸张
*/
public void putInChar(char c);
/**
* 得到输出到纸张上的内容
*/
public String getContent();
}
//我们在开发打印机时,使用了Ink和Paper接口。但并不关心其实现。
public class Printer {
public Ink ink = null;
public Paper paper = null;
public void print(String str){
System.out.println("使用"+
ink .getColor(255,200,0).+"颜色打印");
for(int i=0;i<str.length();++i){// 逐字符输出到纸张
paper .putInChar(str.charat(i));
}
System.out.print( paper .getContent()); // 将纸张的内容输出
}
}
//
3、组装打印机
1、为了方便组装,我们给Printer类的ink和paper属性增加setter方法
public class Printer {
public Ink ink = null;
public Paper paper = null;
... ...
public void setInk (Ink ink) {
this.ink = ink;
}
public void setPaper (Paper paper) {
this.paper = paper;
}
}
2、创建或得到Ink和Paper的实现类
3、使用Spring进行组装
编辑applicationContext.xml文件

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...