我正在学习设计模式教程并遇到装饰器模式。我了解了如何以及何时使用装饰器模式,但是,我对为什么需要从组件派生装饰器感到有点困惑。
我看到的例子如下:
//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
接口(interface)(这里是一个抽象类),以确保 CarDecorator
已经实现(应该覆盖)GetPrice
方法。
如果CarDecorator
不继承自Car
,那么你不能这样做:
Car newCar = new ActualCar();
int price = new CarDecorator(newCar).GetPrice();
Car
在这里的服务非常像一个接口(interface),或者一个明确告诉所有具体装饰器应该实现 GetPrice
方法的契约。
关于c# - 需要从装饰器设计模式中的组件派生装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63252693/