最后是测试了,我们定义一台计算机,由它调用工厂去生产我们需要的打印机,需要什么类型的打印机,就new出对应的工厂,由它来生产我们需要的打印机。
public class Computer
{
private Printer out;
public Computer(Printer out)
{
this.out = out;
}
public void keyIn(String msg)
{
out.getData(msg);
}
public void print()
{
out.out();
}
public static void main(String[] args)
{
PrinterFactory of = new CommonPrinterFactory();
Computer c = new Computer(of.getPrinter());
c.keyIn("hello");
c.keyIn("world");
c.print();
}
}
打印结果:
普通打印机打印: hello
普通打印机打印: world
工厂方法模式仿佛已经很完美的对对象的创建进行了包装,使得客户程序中仅仅处理抽象产品角色提供的接口。那我们是否一定要在代码中遍布工厂呢?大可不必。也许在下面情况下你可以考虑使用工厂方法模式:
面对这种情况,Java 的反射机制与配置文件的巧妙结合突破了限制――这在Spring 中完美的体现了出来。