一个接口 Output
|
1
2
3
4
5
6
7
|
package fact;public interface Output { int MAX_CACHE_LINE=50; void out(); void getData(String msg);} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package fact;public class Printer implements Output{ private String[] printData =new String[MAX_CACHE_LINE]; private int dataNum=0; public void out() { while(dataNum>0) { System.out.println("打印机打印:"+printData[0]); System.arraycopy(printData, 1, printData, 0 , --dataNum); } } public void getData(String msg) { if(dataNum>=MAX_CACHE_LINE) { System.out.println("输出队列已满,添加失败。"); } else { printData[dataNum++]=msg; } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package fact;public class BetterPrinter implements Output{ private String[] printData=new String[MAX_CACHE_LINE*2]; private int dataNum=0; public void out() { while(dataNum>0) { System.out.println("高速打印正在打印:"+printData[0]); System.arraycopy(printData, 1,printData, 0, --dataNum); } } public void getData(String msg) { if(dataNum>=MAX_CACHE_LINE*2) { System.out.println("输出队列已满,添加失败"); } else { printData[dataNum++]=msg; } }} |
功能:新建一个Computer类,能够方便组合上面任一类(Output或BetterOutput):
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package fact;public class Computer { private Output out; public Computer(Output out) { this.out=out; } public void KeyIn(String msg) { out.getData(msg); } public void print() { out.out(); }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package fact;public class OutputFactory { public Output getOutput() { //return new Printer(); return new BetterPrinter(); } public static void main(String[] args) { OutputFactory of=new OutputFactory(); Computer c=new Computer(of.getOutput()); c.KeyIn("wang"); c.KeyIn("da"); c.print(); }} |
Java打印组件设计
473

被折叠的 条评论
为什么被折叠?



