设计模式之工厂模式读后感
作者(大话设计模式)以生动的比喻,从简单工厂模式到工厂模式,最后到抽象工厂模式,极其美妙的描述了工厂模式。
简单工厂模式(以一个简单的加减乘除计算器为例)
初学者代码:
Class Operation{ Double a; Double b; public Double Add(){ return a+b; } public Double Sub(){ return a-b; } public Double Mul(){ return a*b; } }
这样的代码对完成当前的功能没问题,关键是在复用和扩展方面很差,如果要新增一个运算功能,只能去修改类Operation,这是违背修改封闭原则的。
简单工厂实现:
Public Class Operation Private _numA As Double Private _numB As Double Public Property NumA As Double Get Return _numA End Get Set(ByVal value As Double) _numA = value End Set End Property Public Property NumB As Double Get Return _numB End Get Set(ByVal value As Double) _numB = value End Set End Property Public Overridable Function GetResult() Dim result = 0 Return result End Function End Class Public Class AddOperation Inherits Operation Public Overrides Function GetResult() As Object Return Me.NumA + Me.NumB End Function End Class Public Class SubOperation Inherits Operation Public Overrides Function GetResult() As Object Return Me.NumA - Me.NumB End Function End Class Public Class MulOperation Inherits Operation Public Overrides Function GetResult() As Object Return Me.NumA * Me.NumB End Function End Class Public Class OperationFactory Public Shared Function CreateOperation(ByVal op As String) As Operation Dim operation As Operation = Nothing Select Case op Case "+" operation = New AddOperation Case "-" operation = New SubOperation Case "*" operation = New MulOperation Case Else Throw New Exception("操作参数不对") End Select Return operation End Function End Class
这样一来,要扩展新的功能,只需要添加Operation的子类即可,而不必更改已有代码。惟独不舒服的是,要在工厂类中添加Case,这产生了新的模式
简单工厂模式+反射+配置文件,通过配置文件读取操作类型字符串,通过反射生成相应的操作子类实例。现在代码就相当的完美的。