2013-11-02 186 views
0

我已經實現了一個裝飾模式,現在我想寫一個方法「添加裝飾」,這是最好的類/接口有這種方法ICAR或汽車?以及如何將基礎車指向新的裝飾車?裝飾模式

樣品使用:

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

它在接口,隨後將具體類被定義爲好。 –

+0

那麼我是否還需要在抽象裝飾類中實現它呢?那麼第二部分呢? – Desire

+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(); 
+0

我想要它的反義詞, ICar car = new Car(); ICar radial = new Radial(); car.AddDecoration(radial); – Desire

+3

那麼也許你不想裝飾者模式? –