c# - 需要从装饰器设计模式中的组件派生装饰器

标签 c# design-patterns decorator

我正在学习设计模式教程并遇到装饰器模式。我了解了如何以及何时使用装饰器模式,但是,我对为什么需要从组件派生装饰器感到有点困惑。

我看到的例子如下:

//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/

相关文章:

c# - 高级级联删除

c# - 如何在C#中使用SetWindowLong?

php - 使用工厂方法模式比简单工厂有什么优势?

c# - 如何在 C# 中使用这个 Singleton 类?

python - 我应该如何使用 python 装饰器而不更改函数名称?

c# - 如何检测 UI 和 GameObjects 上的点击/触摸事件

c# - Ninject:在每次 Get 调用时调用一个方法

c# - MVP 和多个用户控件

python 属性装饰器

Typescript - 在构造函数装饰器中调用类方法