抽象工厂设计模式是一种创建型设计模式,它提供了一种方式来创建一系列相关或依赖对象,而不需要指定它们具体的类。这种模式在软件工程中非常实用,尤其是在需要将对象的创建与使用分离开来时。
在下面的VB.NET代码示例中,将看到如何实现抽象工厂设计模式。代码展示了如何根据不同的条件创建不同类型的汽车工厂,并从这些工厂中生成不同类型的汽车。
Dim aCarFactory As CarFactory
If aVariable = "Ford" Then
aCarFactory = New FordCarFactory
Else
aCarFactory = New VauxhallCarFactory
End If
Dim aFamilyCar1 As ICar = aCarFactory.CreateFamilyCar
Dim aFamilyCar2 As ICar = aCarFactory.CreateFamilyCar
Dim aCityCar As ICar = aCarFactory.CreateCityCar
首先,定义了一个抽象的汽车工厂类,它包含两个抽象方法:CreateFamilyCar 和 CreateCityCar。这些方法必须由继承自 CarFactory 的具体工厂类来实现。
Public MustInherit Class CarFactory
Public MustOverride Function CreateFamilyCar() As ICar
Public MustOverride Function CreateCityCar() As ICar
End Class
接下来,定义了两个具体的工厂类:FordCarFactory 和 VauxhallCarFactory。这些类继承自 CarFactory 并实现了抽象方法,以创建特定品牌的汽车。
Public Class FordCarFactory Inherits CarFactory
Public Overrides Function CreateCityCar() As ICar
Return New FordCityCar
End Function
Public Overrides Function CreateFamilyCar() As ICar
Return New FordFamilyCar
End Function
End Class
Public Class VauxhallCarFactory Inherits CarFactory
Public Overrides Function CreateCityCar() As ICar
Return New VauxhallCityCar
End Function
Public Overrides Function CreateFamilyCar() As ICar
Return New VauxhallFamilyCar
End Function
End Class
此外,定义了一个汽车接口 ICar,它包含两个方法:Drive 和 Desc。所有具体的汽车类都必须实现这个接口。
Public Interface ICar
Sub Drive()
Function Desc() As String
End Interface
最后,创建了具体的汽车类,如 FordFamilyCar 和 FordCityCar,它们实现了 ICar 接口。这些类定义了 Drive 方法的具体行为,并提供了汽车的描述。
Public Class FordFamilyCar Implements ICar
Public Sub Drive() Implements ICar.Drive
' Drive car
End Sub
Public Function Desc() As String Implements ICar.Desc
Return "Ford Family Car seats 8"
End Function
End Class
Public Class FordCityCar Implements ICar
Public Sub Drive() Implements ICar.Drive
' Drive car
End Sub
Public Function Desc() As String Implements ICar.Desc
Return "Ford City Car seats 2"
End Function
End Class
通过这种方式,抽象工厂设计模式允许根据不同的条件创建不同的汽车对象,而不需要知道它们的具体实现。这提高了代码的灵活性和可维护性。