3 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
這將是添加裝飾器的好地方。一些偽代碼(不完整!)但希望您能明白。
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 } }
然后在您的程序中創(chuàng)建您的汽車并使用 VehicleWithAc 裝飾器對(duì)其進(jìn)行裝飾
Program
var baseCar = new Car();
var summerDriver = new VehicleWithAc(baseCar)

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
我認(rèn)為你遇到的問題是你fuelConsumption作為單個(gè)變量傳遞給構(gòu)造函數(shù),從而說明
這是汽車的油耗,完全停止。
正如您所發(fā)現(xiàn)的,解決這個(gè)問題 - 燃油消耗不是一個(gè)靜態(tài)的東西,它取決于其他變量,例如空調(diào)是否打開。Doug 已經(jīng)接近提到裝飾器了,但我認(rèn)為它可以更簡單一些,但更靈活。
我認(rèn)為您仍然應(yīng)該傳遞一個(gè)燃油消耗數(shù)據(jù),為了簡單起見,我們將其稱為baseFuelConsumption。請(qǐng)記住,車輛通常根據(jù)城市和高速公路的燃油消耗進(jìn)行分級(jí),因?yàn)樗鼈兺ǔ2煌?,但出于此目的,我們將忽略它?/p>
拋開行駛距離等,我們有:
public abstract class Vehicle
{
private readonly double _baseFuelConsumption;
protected double BaseFuelConsumption => _baseFuelConsumption;
protected Vehicle(double baseFuelConsumption) => _baseFuelConsumption = baseFuelConsumption;
public virtual double ActualFuelConsumption => BaseFuelConsumption;
}
那么,空調(diào)會(huì)額外消耗多少油耗呢?讓我們以 Doug 的答案為基點(diǎn),并將其賦予我們的汽車......
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;
}
}
}
現(xiàn)在,為了進(jìn)行模擬,您可以隨著時(shí)間的推移打開和關(guān)閉交流電,并ActualFuelConsumption隨著時(shí)間的推移測量屬性。

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您想使用此結(jié)構(gòu),您必須為屬性設(shè)置自定義規(guī)則。
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);
}
因?yàn)槟念愂浅橄蟮?,并且派生類中的屬性沒有可重寫的屬性,所以您無法訪問基屬性。例如,您可以在集合中使用條件
public double FuelConsumption {
get { return _fuelConsumption; }
protected set {
if(Issummer)
{
_fuelConsumption = (_fuelConsumption + 0.9);
}else{ _fuelConsumption =_fuelConsumption;}
} }
- 3 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報(bào)