我有一个装饰器模式的实现,现在我想写一个“添加装饰”方法,哪个是最好的类/接口来拥有这个方法 ICar 或 Car?以及如何将基本车指向新装饰车?
样品用途:
ICar car=new Car();
ICar radial= new Radial();
car.AddDecoration(radial);
interface ICar
{
int Speed { get; set; }
void Accelerate();
}
class Car : ICar
{
private int speed = 0;
public int Speed
{
get
{
return speed;
}
set
{
speed = value;
}
}
public virtual void Accelerate()
{
Speed += 5;
}
}
abstract class CarModification : ICar
{
private ICar modifiedCar;
public ICar ModifiedCar
{
get { return modifiedCar; }
set { modifiedCar = value; }
}
public virtual int Speed
{
get
{
return modifiedCar.Speed;
}
set
{
modifiedCar.Speed = value;
}
}
public void Accelerate()
{
modifiedCar.Accelerate();
}
}
class Radial : CarModification
{
public void Accelerate()
{
base.Accelerate();
Speed += 1;
}
}