Factory






4.50/5 (4投票s)
工厂设计模式的任务是创建具体的子类。你可以在整个 .NET 中看到工厂设计模式的应用。
引言
工厂设计模式的任务是创建具体的子类。你可以在整个 .NET Framework 中看到工厂设计模式的应用。
工厂模式的本质是“定义一个创建对象的接口,但让子类决定实例化哪个类。工厂方法允许一个类将实例化推迟到子类。”
工厂方法封装了对象的创建过程。如果创建过程非常复杂,例如依赖于配置文件中的设置或用户输入,这会很有用。
C# 和 VB.NET 中工厂模式的示例
// A Simple Interface
public interface IVehicle
{
void Drive(int miles);
}
// The Vehicle Factory
public class VehicleFactory
{
public static IVehicle getVehicle(string Vehicle)
{
switch (Vehicle) {
case "Car":
return new Car();
case "Lorry":
return new Lorry();
default:
throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
break;
}
}
}
// A Car Class that Implements the IVehicle Interface
public class Car : IVehicle
{
public void IVehicle.Drive(int miles)
{
// Drive the Car
}
}
// A Lorry Class that Implements the IVehicle Interface
public class Lorry : IVehicle
{
public void IVehicle.Drive(int miles)
{
// Drive the Lorry
}
}
' A Simple Interface
Public Interface IVehicle
Sub Drive(ByVal miles As Integer)
End Interface
' The Vehicle Factory
Public Class VehicleFactory
Public Shared Function getVehicle(ByVal Vehicle As String) As IVehicle
Select Case Vehicle
Case "Car"
Return New Car
Case "Lorry"
Return New Lorry
Case Else
Throw New ApplicationException(String.Format("Vehicle '{0}' cannot be created", Vehicle))
End Select
End Function
End Class
' A Car Class that Implements the IVehicle Interface
Public Class Car
Implements IVehicle
Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive
' Drive the Car
End Sub
End Class
' A Lorry Class that Implements the IVehicle Interface
Public Class Lorry
Implements IVehicle
Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive
' Drive the Lorry
End Sub
End Class