3 回答
TA贡献1860条经验 获得超9个赞
这将是添加装饰器的好地方。一些伪代码(不完整!)但希望您能明白。
public class VehicleDecorator : Vehicle
public VehicleDecorator(Vehicle vehicle)
{
this.vehicle = vehicle;
}
public class VehicleWithAc : VehicleDecorator
public VehicleWithAc(Vehicle vehicle) : base(vehicle){}
public override double FuelConsumption {
get{
return base.FuelConsumption+0.9 } }
然后在您的程序中创建您的汽车并使用 VehicleWithAc 装饰器对其进行装饰
Program
var baseCar = new Car();
var summerDriver = new VehicleWithAc(baseCar)
TA贡献1873条经验 获得超9个赞
我认为你遇到的问题是你fuelConsumption作为单个变量传递给构造函数,从而说明
这是汽车的油耗,完全停止。
正如您所发现的,解决这个问题 - 燃油消耗不是一个静态的东西,它取决于其他变量,例如空调是否打开。Doug 已经接近提到装饰器了,但我认为它可以更简单一些,但更灵活。
我认为您仍然应该传递一个燃油消耗数据,为了简单起见,我们将其称为baseFuelConsumption。请记住,车辆通常根据城市和高速公路的燃油消耗进行分级,因为它们通常不同,但出于此目的,我们将忽略它。
抛开行驶距离等,我们有:
public abstract class Vehicle
{
private readonly double _baseFuelConsumption;
protected double BaseFuelConsumption => _baseFuelConsumption;
protected Vehicle(double baseFuelConsumption) => _baseFuelConsumption = baseFuelConsumption;
public virtual double ActualFuelConsumption => BaseFuelConsumption;
}
那么,空调会额外消耗多少油耗呢?让我们以 Doug 的答案为基点,并将其赋予我们的汽车......
public class Car : Vehicle
{
private const double _ACModifier = 0.9;
public Car()
:base(1)
{
}
public bool IsACOn { get; set; }
public override double ActualFuelConsumption
{
get
{
double consumption = base.ActualFuelConsumption;
consumption += IsACOn ? _ACModifier : 0;
return consumption;
}
}
}
现在,为了进行模拟,您可以随着时间的推移打开和关闭交流电,并ActualFuelConsumption随着时间的推移测量属性。
TA贡献1794条经验 获得超7个赞
如果您想使用此结构,您必须为属性设置自定义规则。
public abstract class Vehicle
{
protected Vehicle(double fuelQuantity, double fuelConsumption)
{
this.FuelQuantity = fuelQuantity;
this._fuelConsumption = fuelConsumption;
this.FuelConsumption = fuelConsumption;
}
public double FuelQuantity { get; protected set; }
private double _fuelConsumption { get; set; }
public double FuelConsumption {
get { return _fuelConsumption; }
protected set {
_fuelConsumption = (_fuelConsumption + 0.9);
} }
public abstract string Drive(double distance);
public abstract void Refuel(double liters);
}
因为您的类是抽象的,并且派生类中的属性没有可重写的属性,所以您无法访问基属性。例如,您可以在集合中使用条件
public double FuelConsumption {
get { return _fuelConsumption; }
protected set {
if(Issummer)
{
_fuelConsumption = (_fuelConsumption + 0.9);
}else{ _fuelConsumption =_fuelConsumption;}
} }
- 3 回答
- 0 关注
- 103 浏览
添加回答
举报