
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
5.3 使用简单工厂模式封装产品创建细节
接下来看代码,还是以课程为例。咕泡学院目前开设有Java架构、大数据、人工智能等课程,已经形成了一个生态。我们可以定义一个课程标准ICourse接口。

创建一个Java课程的实现类JavaCourse。

客户端调用代码如下。

由上面代码可知,父类ICourse指向子类JavaCourse的引用,应用层代码需要依赖JavaCourse。如果业务扩展,则继续增加PythonCourse,甚至更多,那么客户端的依赖会变得越来越臃肿。因此,我们要想办法把这种依赖减弱,把创建细节隐藏。虽然在目前的代码中,创建对象的过程并不复杂,但从代码设计角度来讲不易于扩展。因此,用简单工厂模式对代码进行优化。首先增加课程PythonCourse类。

然后创建CourseFactory工厂类。

最后修改客户端调用代码。

当然,为了调用方便,可将CourseFactory的create()方法改为静态方法,其类图如下。

客户端调用虽然简单了,但如果业务继续扩展,要增加前端课程,则工厂中的create()方法就要随着产品链的丰富每次都要修改代码逻辑,这不符合开闭原则。因此,我们可以采用反射技术继续对简单工厂模式进行优化,代码如下。

客户端调用代码修改如下。

优化之后,产品不断丰富,不需要修改CourseFactory中的代码。但问题是,方法参数是字符串,可控性有待提升,而且还需要强制转型。继续修改代码。

优化客户端测试代码。

最后来看如下图所示的类图。
