0

我有一个装饰器模式的实现,现在我想写一个“添加装饰”方法,哪个是最好的类/接口来拥有这个方法 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;
        }
    }
4

1 回答 1

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();
于 2013-11-02T12:30:13.150 回答