我让我们说一个类,VehicleManager。 此类管理Vehicle类型对象的生命周期和调用。车辆充当模块并扩展基础车辆类,这是抽象的。
因此,如果你制作一辆自行车,你永远不会做新的Bike(),你做的是VehicleManager->创建(' Bike',5);
我的问题是,我希望每辆车的构造都能接收预定义的参数,并做一些预定义的动作,所以我的基础Vehicle类有一个私有的最终构造函数。
示例:
Private Sub btnSave_Click()
Dim strAddNewConsumable As String
Dim strCompany As String
Dim strConName As String
Dim strConID As String
Dim strCboConSupplier As String
Dim strConTargetLevel As String
Dim strConCost As String
strCompany = Me.ConCompany
strConName = Me.txtConName
strConID = Me.txtConID
strCboConSupplier = Me.CboConSupplier
strConTargetLevel = Me.txtConTargetLevel
strConCost = Me.txtConCost
strAddNewConsumable = "INSERT INTO ConTblConsumables(strConCost, ConName, ConExtraID, Supplier, ConTargetLevel, Cost)" _
& "VALUES('" & strCompany & "', '" & strConName & "', '" & strConID & "', '" & strCboConSupplier & "', '" & strConTargetLevel & "', '" & strConCost & "')"
CurrentDb.Execute (strAddNewConsumable)
MsgBox "Record Inserted", vbExclamation
End Sub
但我仍然希望每种车型都有一些自定义初始化
所以做完后
final private function __construct(Array $myCustomData){
$this->customData = $myCustomData;
}
我在做
$newVehicle = new $ClassName($myCustomData);
这可以接受吗?感谢
答案 0 :(得分:0)
您可以使用多种模式在项目中生成车辆,查看AbstractFactory或FactoryMethod。可以根据您的程序上下文使用它们。这是AbstractFactory示例:
// Vehicle classes
class Vehicle
{
};
class Car extends Vehicle
{
};
class Bike extends Vehicle
{
};
//Abstract factory classes
abstract class VehicleFactory
{
abstract protected function GetVehicle( $customData );
};
class CarFactory extends VehicleFactory
{
public function GetVehicle( $customData )
{
//Do special init
return new Car();
}
};
class BikeFactory extends VehicleFactory
{
public function GetVehicle( $customData )
{
//Do special init
return new Bike();
}
};
//Program context classes
class RaceTrack
{
public function GenerateRacers( VehicleFactory $factory )
{
//$factory->GetVehicle(array());
}
public function AddRacers( Vehicle $vehicle )
{
}
};
$CarFact = new CarFactory();
$RaceTrack = new RaceTrack();
$RaceTrack->GenerateRacers($CarFact);
这是Factory方法的示例:
//Factory method pattern
class VehicleFactory2
{
const BIKE_TYPE = 0;
const CAR_TYPE = 1;
public function GetVehicle( $type, $customData )
{
if ( $type == self::BIKE_TYPE )
{
return new Bike($customData);
}
else if ( $type == self::CAR_TYPE )
{
return new Car($customData);
}
return null;
}
};
$VehicleFact = new VehicleFactory2();
$RaceTrack2 = new RaceTrack();
$RaceTrack2->AddRacers($VehicleFact->GetVehicle(VehicleFactory2::CAR_TYPE, array()));
DI可用作构建者,方法,二者注射剂。使用DI使您的项目更加灵活是一种很好的做法