前言
在设计模式-简单工厂文章中介绍的简单工厂,我们发现,如果在此基础上新增加一种图表的展示,那么就得修改静态工厂的generateChartImpl()方法。这无疑违反了开放封闭原则。
修改Factory
于是在简单工厂的基础上我定义了一个IChartFactory的接口,如下。1
2
3
4
5interface IChartFactory {
fun generateChartImpl(): IChart
}
拆分Factory
然后将简单工厂的ChartFactory拆分成下面的类,如下。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class PieChartFactory : IChartFactory {
override fun generateChartImpl(): IChart = PieChart()
}
class BarChartFactory : IChartFactory {
override fun generateChartImpl(): IChart = BarChart()
}
class LinearChartFactory : IChartFactory {
override fun generateChartImpl(): IChart = LinearChart()
}
测试
使用起来只需要通过对应的Factory创建对应的IChart对象就可以了。如下1
2
3
4fun main(args: Array<String>) {
val chartImpl = PieChartFactory().generateChartImpl()
chartImpl.display()
}
并且我们还发现,如果需要增加一种图表的显示只需要增加IChart的子类和对应的IChartFactory的子类就可以了,而不需要去修改已有的代码,这样就不会违反开闭原则了,而且具有一定的扩展性。
总结
从上面的代码中我们看出,虽然工厂方法能够有很好的扩展性,但是缺点也显而易见,它会导致类的数量越来越多,这样反而会增加系统的复杂度。
毒鸡汤
日子还长,请别失望~