我是这个装饰模式的实现,现在我想写一个方法"添加装饰",这是使用这种方法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;
}
}
答案 0 :(得分:3)
interface ICar
{
int Speed { get; set; }
void Accelerate();
}
class Car : ICar
{
public int Speed { get; set; }
public virtual void Accelerate()
{
Speed += 5;
}
}
class Radial : ICar
{
private readonly ICar modified;
Radial(ICar modified)
{
this.modified = modified;
}
public int Speed
{
get { return modified.Speed;
set { modified.Speed = value; }
}
public void Accelerate()
{
modified.Accelerate();
modified.Speed += 1;
}
}
ICar car = new Radial(new Car());
car.Accelerate();