抽象类和工厂方法 [英] Abstract Classes and Factory Method

查看:95
本文介绍了抽象类和工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.

我正在寻找实现以下目标的好方法:

我有一个抽象类车辆.车辆有多个孩子:自行车,汽车,卡车.

所有公共元素都包含在父类中,该父类还具有一个指示类型的字段(如果可以的话,则为鉴别符).

汽车和卡车可以牵引物体(在此示例中,自行车不能牵引).这些其他对象需要对Car \ Truck可用,但对自行车不可用.

自行车,汽车和卡车都有各自独特的领域.

现在,通过使用Factory方法,您将创建如下所示的内容:

Hi there.

I am looking for a good way to implement the following:

I have an Abstract Class Vehicle. Vehicle has several children: Bike, Car, Truck.

All common elements are contained within the parent class which also have a field to indicate the type (a discriminator if you will).

A Car and Truck can tow objects (a bike cannot in this example). These other object need to be available to a Car\Truck but not the Bike.

A Bike, Car and Truck each have fields that are unique to them.

Now by using the Factory Method, you would create do something like this:

Vehicle myVehicle = myVehicleFactory(String typeOfVehicle)



要获得所需类型的车辆,具体取决于您传递给工厂的类型.在工厂内,将返回创建的所有新实例,然后将其强制转换为Vehicle类.我的问题是:现在我无法通过使用myVehcile点来访问子级特定的属性\方法...无论如何,只有公用的属性\字段\方法才可用.

换句话说:我无法将汽车或卡车拖曳的对象链接到myVehicle类.如何解决此问题(请注意,将来可能会添加其他新的车辆类型)

感谢



to get a vehicle of the type you need depending on the type you pass along to the factory. Within the factory, any new instances that are created is returned but then cast into a Vehicle class. The problem I have is this: I now cannot access child specific properties\methods by using myVehcile dot whatever... Only the common properties\fields\methods are available.

In other words: I cannot link up the object being towed by a Car or Truck to the myVehicle class. How do I get around this problem (noting that in the future other new vehicle type may be added)

Thanks

推荐答案

充分利用 ^ ]运算符.

Make use of the as[^] operator.

Car myCar = myVehicle as Car;
if (myCar != null)
{
    // Call methods specific to Car class.

}


哈哈.我想通了!

我只需要将mVehicle投放到我称之为工厂的汽车,自行车或卡车上即可.

例如:

我有
Ha ha. I figured it out!

I simply need to cast mVehicle to a car, bike or truck where i call the factory.

For example:

I have
Vehicle myVehicle = myVehicleFactory(String typeOfVehicle)



如果我的类型是自行车",那么我会这样做:



if my type is ''bike'' then i do this:

Bike myBike = (Bike)myVehicleFactory("bike");



或者是卡车



or if it is a truck

Truck myTruck = (Truck)myVehicleFactory("truck");



现在还不完全是亚纯的,但是您可以使用其他技术来确定要构建的具体类型.



and this now NOT completely polomorphic but you can kinda use other techniques to determine the concrete type you want to build.


这篇关于抽象类和工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆