
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
6.2 使用工厂方法模式实现产品扩展
工厂方法模式主要解决产品扩展的问题,在简单工厂中,随着产品链的丰富,如果每个课程的创建逻辑都有区别,则工厂的职责会变得越来越多,有点像万能工厂,并不便于维护。根据单一职责原则,我们将职能继续拆分,专人干专事。Java课程由Java工厂创建,Python课程由Python工厂创建,对工厂本身也做抽象。首先创建ICourseFactory接口。

然后分别创建子工厂,JavaCourseFactory类的代码如下。

PythonCourseFactory类的代码如下。

客户端测试代码如下。

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