package com.fsti.factory.factorymethod;
public interface Output {
public final static Integer MAX_CACHE_LINE = 3;
void getData(String str);
void out();
}
package com.fsti.factory.factorymethod;
public class Printer implements Output {
private String[] printData = new String[MAX_CACHE_LINE];
// 用以记录当前需打印的作业数
private int dataNum = 0;
public void getData(String str) {
if (dataNum >= MAX_CACHE_LINE) {
System.out.println("输出队列一满,添加失败");
} else {
printData[dataNum++] = str;
}
}
public void out() {
while (dataNum > 0) {
System.out.println("打印机打印:" + printData[0]);
// 把作业整体前移一位,并将剩下的作业数减一
System.arraycopy(printData, 1, printData, 0, --dataNum);
}
}
}
package com.fsti.factory.factorymethod;
public class BetterPrinter implements Output {
private String[] printData = new String[MAX_CACHE_LINE];
// 用以记录当前需打印的作业数
private int dataNum = 0;
public void getData(String str) {
if (dataNum >= MAX_CACHE_LINE) {
System.out.println("输出队列一满,添加失败");
} else {
printData[dataNum++] = str;
}
}
public void out() {
while (dataNum > 0) {
System.out.println("Better打印机打印:" + printData[0]);
// 把作业整体前移一位,并将剩下的作业数减一
System.arraycopy(printData, 1, printData, 0, --dataNum);
}
}
}
package com.fsti.factory.factorymethod;
public interface OutputFactory {
Output getOutput();
}
package com.fsti.factory.factorymethod;
public class BetterPrinterFactory implements OutputFactory {
public Output getOutput() {
return new BetterPrinter();
}
}
package com.fsti.factory.factorymethod;
public class PrinterFactory implements OutputFactory {
public Output getOutput() {
return new Printer();
}
}
package com.fsti.factory.factorymethod;
public class Computer {
private Output out;
public Computer(Output out) {
this.out = out;
}
public void keyIn(String str) {
out.getData(str);
}
public void print() {
out.out();
}
public static void main(String[] args) {
// 客户端代码成功是与被调用对象的实现类分类
// 但带来了另一种耦合:客户端代码与不同的工厂类耦合
OutputFactory of = null;
String type = "better";
if (type.equals("better")) {
of = new BetterPrinterFactory();
} else {
of = new PrinterFactory();
}
Computer c = new Computer(of.getOutput());
c.keyIn("工厂模式之");
c.keyIn("工厂方法模式");
c.print();
}
}
采用工厂方法设计的架构,客户端代码成功是与被调用对象的实现类分类,但带来了另一种耦合:客户端代码与不同的工厂类耦合。