工厂模式是一种典型的解耦设计模式,可以降低代码各模块之间的耦合性,提高代码的维护性。如何更深入的理解这句话的含义以及工厂模式的核心又是什么?下面通过一个例子进行讲述。
(为更好的理解这篇文章,需要了解 继承 组合 多态 以及 接口相关基础知识,在此不再做介绍)
案例背景:
假设目前所有的打印机设备都具有数据输入getData()与数据输出out()功能,可以将此公共行为抽象为OutPut接口,HP和Mi是两家不同的生产厂商,分别定义为HpPrinter和MiPrinter 两个类,在类中将对getData()与out()进行具体的实现。目前存在一个电脑类 Computer 利用组合的方式添加打印机功能。
如果目前我们采用的HpPrinter 可以如下构造Computer类:
class Computer
{
private HpPrinter hpriter;
public Computer(HpPrinter hpriter)
{
this.hpriter = hpriter;
}
public void keyIn()
{
hpriter.getData();
}
public void print()
{
hprinter.out();
}
// TO DO ...
}
其中 Computer类与HpPrinter类紧密耦合,如果目前发现MiPrinter具有更佳的功能,则需要对Computer类进行修改,代码维护起来非常的麻烦!那么 工厂模式又是如何解耦合的呢?
为此,我们在创建一个 OutPutFactory 类,用于生产Output 对象。并将Computer类修改为:
class Computer
{
private OutPut output;
public Computer(OutPut output)
{
this.output = output;
}
public void keyIn()
{
output.getData();
}
public void print()
{
output.out();
}
// TO DO ...
}
UML 类图 如下图所示:
借助于OutPutFactory类可以有效的解耦合,Computer类与HpPrinter、MiPrinter类没有直接的关联,只与OutPut相关。在OutPutFactory类中的CreatureOutput方法可以创建HpPrinter对象或者MiPrinter对象。注意文字标红的位置!函数的返回类型是OutPut !
OutPut output = new HpPrinter(); // 工厂模式的核心要领 ,向上转型 多态!
OutPut output = new MiPrinter();
new HpPrinter()创建的是HpPrinter类对象,其向上转型 赋值的对象为OutPut类,在调用方法时利用了多态性质。这也就是工厂模式的核心所在!