用decorate模式畫一張畫

來源:互聯網
上載者:User
用decorate模式畫一張畫

我對decorate模式的理解:
1-首先要有一個Interface,提供一個通用的方法;
2-其次有n多個class來實現這個介面中的方法,這些實現方法在功能上應該是並列的,但不是必須的,從而可以根據需要decorate那個需要被修飾的初始對象。
3-最後這些class都有一個帶有Interface作為參數的構造方法和一個Interface的屬性,這樣在構造的時候就可以取得那個需要修飾的對象的執行個體,然後在實現Interface的方法裡面,首先實現修飾對象執行個體的修飾方法,然後再進行自己的decorate方法。

根據這個想法來畫一張畫:

package  test;

public   interface  Painting  {
     public   void  paint();
}

class  SunPainting  implements  Painting  {
    Painting painting  =   null ;

     public  SunPainting()  {
    }

     public  SunPainting(Painting painting)  {
         this .painting  =  painting;
    }

     public   void  paint()  {
         if  (painting  !=   null )  {
            painting.paint();
        }
        System.out.println( " 畫了一個太陽 " );
    }
}

class  CloudPainting  implements  Painting  {
    Painting painting  =   null ;

     public  CloudPainting()  {
    }

     public  CloudPainting(Painting painting)  {
         this .painting  =  painting;
    }

     public   void  paint()  {
         if  (painting  !=   null )  {
            painting.paint();
        }
        System.out.println( " 畫了一朵白雲 " );
    }
}

class  LawnPainting  implements  Painting  {
    Painting painting  =   null ;

     public  LawnPainting()  {
    }

     public  LawnPainting(Painting painting)  {
         this .painting  =  painting;
    }

     public   void  paint()  {
         if  (painting  !=   null )  {
            painting.paint();
        }
        System.out.println( " 畫了一片草地 " );
    }
}

再寫段測試畫畫的代碼:

package  test;

public   class  TestPainting  {
     public   static   void  main(String[] args) {
         new  SunPainting( new  CloudPainting( new  LawnPainting())).paint();
    }
}

測試結果:

畫了一片草地
畫了一朵白雲
畫了一個太陽

 最後有個問題:為什麼不直接定義一個畫畫的類,然後把這些該怎麼畫的事情分別通過方法來實現呢? 那麼什麼情況下使用decorate模式更為合適呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.