【发布时间】:2020-11-24 21:25:42
【问题描述】:
我正在阅读设计模式教程并遇到了装饰器模式。我知道如何以及何时使用装饰器模式,但我对为什么需要从组件派生装饰器感到有些困惑。
我看到的例子如下:
//Component classes
public abstract class Car
{
public abstract int GetPrice();
//Other properties and methods
}
public class ActualCar : Car
{
public int GetPrice(){return 1000;}
}
//Decorators classes
public class CarDecorator : Car //No idea why this is necessary
{
protected Car car;
public CarDecorator(Car car)
{
this.car = car;
}
public override int GetPrice() => this.car.GetPrice();
}
public class LeatherSeats : CarDecorator
{
public LeatherSeats(Car car) : base(car){}
public override int GetPrice() => this.car.GetPrice() + 200;
}
public class AlloyWheels : CarDecorator
{
public AlloyWheels(Car car) : base(car) {}
public override int GetPrice() => this.car.GetPrice() + 150;
}
现在,当使用组件及其装饰器时,我们将其用作:
Car newCar = new ActualCar();
int price = new AlloyWheels(new LeatherSeats(newCar)).GetPrice();
现在我觉得 CarDecorator 继承自 Car 很奇怪,因为无论你怎么看它都不遵循 is-a 类型的关系。所以我又看了几个例子,意识到这就是装饰器模式的设计方式。
我不想质疑这样设计装饰器模式的原因,只是想知道不从它包装的组件中派生装饰器模式会有什么缺点。
【问题讨论】:
-
如果
CarDecorator没有从Car继承,你会怎么写...int price = new AlloyWheels(new LeatherSeats(newCar)).GetPrice();? -
如何“不遵循 is-a 关系”?添加合金轮毂不会让汽车不再是汽车,没有必要添加合金轮毂......
-
我认为您的代码中有错字,
ActualCar不应该继承自Car吗? -
@quaabaam,谢谢你的错字,我更新了我的代码。
-
@AlexeiLevenkov 从 Car 派生 AlloyWheels 看起来好像 AlloyWheels 是一种汽车,这是没有意义的,因为合金轮毂可以很好地与 Car 分开。 Car 的属性,例如。 GasType 将不适用于 AlloyWheels。
标签: c# design-patterns decorator